SlideShare a Scribd company logo
1 of 3
Download to read offline
pi.rb                                                                          Page 1 of 3
    1:   #! /usr/bin/env jruby
    2:
    3:   # First things first.
    4:   # Load Java integration support
    5:   require "java"
    6:
    7:   # Add ’lib’ in the same directory as this file to the load path
    8:   $: << File.join(File.dirname(__FILE__), ’lib’)
    9:
   10:   # Load Java libraries
   11:   require ’scala-library’
   12:   require ’akka/akka-actor-1.1.2’
   13:
   14:   # Here, we import Java classes so that we don’t have to prefix them
   15:   # with Java::.
   16:   java_import ’akka.actor.Actors’
   17:   java_import ’akka.actor.ActorRef’
   18:   java_import ’akka.actor.UntypedActor’
   19:   java_import ’akka.actor.UntypedActorFactory’
   20:   java_import ’akka.routing.CyclicIterator’
   21:   java_import ’akka.routing.InfiniteIterator’
   22:   java_import ’akka.routing.Routing’
   23:   java_import ’akka.routing.UntypedLoadBalancer’
   24:   # Java’s built-in classes don’t need to be quoted (for a String)
   25:   java_import java.util.concurrent.CountDownLatch
   26:
   27:   # Convenience method for creating an Actor
   28:   def actorOf(&code)
   29:     Actors.actorOf(Class.new do
   30:                      include UntypedActorFactory
   31:                      define_method(:create) do |*args|
   32:                        code[*args]
   33:                      end
   34:                    end.new)
   35:   end
   36:
   37:   class Calculate; end
   38:   # Struct.new(...) creates an instance having the instance variables
   39:   # passed
   40:   class Work < Struct.new(:start, :nrOfElements); end
   41:   class Result < Struct.new(:value); end
   42:
   43:   class Worker < UntypedActor
   44:     # needed by actorOf
   45:     def self.create(*args)
   46:       new *args
   47:     end
   48:
   49:    # define the work
   50:    def calculatePiFor(start, nrOfElements)
   51:      # Here, we are using the identity
   52:      # Pi = 4 * sum_{k=0}^{infty} (-1)^k/(2 k + 1)
   53:      # We divide the work into chunks of nrOfElements
   54:      # Enumerable#inject may be a little foreign for Java programmers, but
   55:      # it can be thought of as a shorthand for looping and re-assigning
   56:      # the value of the block inside to the memo varialbe ("acc" in this case)
   57:      # "M...N" means a Range starting at M, ending *1 before* N.
   58:      ((start * nrOfElements)...((start + 1) * nrOfElements)).inject(0) do |acc,i|
   59:        acc + 4.0 * (1 - (i.modulo 2) * 2) / (2 * i + 1)
   60:      end
   61:    end
   62:
   63:    # message handler
   64:    def onReceive(message)
   65:      # examining the class of an object is not very Ruby-esque.
pi.rb                                                                         Page 2 of 3
   66:       # in generatl, Rubyists prefer duck typing
   67:       if message.kind_of? Work
   68:         work = message
   69:
   70:         # perform the work
   71:         result = calculatePiFor(work.start, work.nrOfElements)
   72:
   73:         # reply with the result
   74:         context.replyUnsafe(Result.new(result))
   75:
   76:       else
   77:         raise IllegalArgumentException.new "Unknown message [#{message + b}]"
   78:       end
   79:     end
   80:   end
   81:
   82:   class PiRouter < UntypedLoadBalancer
   83:     attr_reader :seq
   84:
   85:     def initialize(workers)
   86:       super() # make sure the underlying Java proxy is properly initialized
   87:       @seq = CyclicIterator.new(workers)
   88:     end
   89:   end
   90:
   91:   class Master < UntypedActor
   92:     def initialize(nrOfWorkers, nrOfMessages, nrOfElements, latch)
   93:       super()
   94:       @nrOfMessages, @nrOfElements, @latch = nrOfMessages, nrOfElements, latch
   95:       @nrOfResults, @pi = 0, 0.0
   96:
   97:       # create the workers
   98:       workers = java.util.ArrayList.new
   99:       nrOfWorkers.times { workers << Actors.actorOf(Worker).start }
  100:
  101:      # wrap them with a load-balancing router
  102:      @router = actorOf { PiRouter.new(workers) }.start
  103:    end
  104:
  105:    # message handler
  106:    def onReceive(message)
  107:      if message.kind_of? Calculate
  108:        # schedule work
  109:        @nrOfMessages.times do |start|
  110:          @router.sendOneWay(Work.new(start, @nrOfElements), context)
  111:        end
  112:
  113:        # send a PoisonPill to all workers telling them to shut down themselves
  114:        @router.sendOneWay(Routing::Broadcast.new(Actors.poisonPill))
  115:
  116:        # send a PoisonPill to the router, telling him to shut himself down
  117:        @router.sendOneWay Actors.poisonPill
  118:      elsif message.kind_of? Result # handle result from the worker
  119:        @pi += message.value
  120:        @nrOfResults += 1
  121:        context.stop if @nrOfResults == @nrOfMessages
  122:      else
  123:        raise IllegalArgumentException.new "Unknown message [#{message}]"
  124:      end
  125:    end
  126:
  127:    def preStart
  128:      @start = java.lang.System.currentTimeMillis
  129:    end
  130:
pi.rb                                                                         Page 3 of 3
  131:     def postStop
  132:       # tell the world that the calculation is complete
  133:       puts format("ntPi estimate: tt%sntCalculation time: t%s millis",
  134:           @pi, (java.lang.System.currentTimeMillis - @start))
  135:       @latch.countDown
  136:     end
  137:   end
  138:
  139:
  140:   class Pi
  141:     def self.calculate(nrOfWorkers, nrOfElements, nrOfMessages)
  142:       # this latch is only plumbing to know when the calculation is completed
  143:       latch = CountDownLatch.new(1)
  144:
  145:       # create the master
  146:       master = Actors.actorOf do
  147:         Master.new(nrOfWorkers.to_i, nrOfMessages.to_i, nrOfElements.to_i, latch)
  148:       end.start
  149:       master.sendOneWay(Calculate.new) # start the calculation
  150:       latch.await # wait for master to shut down
  151:     end
  152:   end
  153:
  154:   # Ready to do the real work
  155:   if (ARGV.length < 3)
  156:     exit "Usage: $0 num_workers num_elements num_messages"
  157:   end
  158:
  159:   Pi.calculate(*ARGV[0..2])

More Related Content

What's hot

Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryMauro Rocco
 
DSLs Internas e Ruby
DSLs Internas e RubyDSLs Internas e Ruby
DSLs Internas e RubyFabio Kung
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task QueueDuy Do
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Innovation and Security in Ruby on Rails
Innovation and Security in Ruby on RailsInnovation and Security in Ruby on Rails
Innovation and Security in Ruby on Railstielefeld
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsSteven Evatt
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To BatchLuca Mearelli
 
The road to Ember.js 2.0
The road to Ember.js 2.0The road to Ember.js 2.0
The road to Ember.js 2.0Codemotion
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With PythonLuca Mearelli
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your AppLuca Mearelli
 
Testing Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyTesting Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyMatthew Beale
 
More tips n tricks
More tips n tricksMore tips n tricks
More tips n tricksbcoca
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGuillaume Laforge
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansiblebcoca
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpathAlexis Hassler
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 

What's hot (20)

Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
DSLs Internas e Ruby
DSLs Internas e RubyDSLs Internas e Ruby
DSLs Internas e Ruby
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Innovation and Security in Ruby on Rails
Innovation and Security in Ruby on RailsInnovation and Security in Ruby on Rails
Innovation and Security in Ruby on Rails
 
JRuby and You
JRuby and YouJRuby and You
JRuby and You
 
Django Celery
Django Celery Django Celery
Django Celery
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain Points
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
The road to Ember.js 2.0
The road to Ember.js 2.0The road to Ember.js 2.0
The road to Ember.js 2.0
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
Testing Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyTesting Ember Apps: Managing Dependency
Testing Ember Apps: Managing Dependency
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
More tips n tricks
More tips n tricksMore tips n tricks
More tips n tricks
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansible
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 

Similar to Pi

Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbJuan Maiz
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoNina Zakharenko
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی Mohammad Reza Kamalifard
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Coffee script
Coffee scriptCoffee script
Coffee scripttimourian
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 

Similar to Pi (20)

Celery with python
Celery with pythonCelery with python
Celery with python
 
Celery
CeleryCelery
Celery
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Why ruby
Why rubyWhy ruby
Why ruby
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Pi

  • 1. pi.rb Page 1 of 3 1: #! /usr/bin/env jruby 2: 3: # First things first. 4: # Load Java integration support 5: require "java" 6: 7: # Add ’lib’ in the same directory as this file to the load path 8: $: << File.join(File.dirname(__FILE__), ’lib’) 9: 10: # Load Java libraries 11: require ’scala-library’ 12: require ’akka/akka-actor-1.1.2’ 13: 14: # Here, we import Java classes so that we don’t have to prefix them 15: # with Java::. 16: java_import ’akka.actor.Actors’ 17: java_import ’akka.actor.ActorRef’ 18: java_import ’akka.actor.UntypedActor’ 19: java_import ’akka.actor.UntypedActorFactory’ 20: java_import ’akka.routing.CyclicIterator’ 21: java_import ’akka.routing.InfiniteIterator’ 22: java_import ’akka.routing.Routing’ 23: java_import ’akka.routing.UntypedLoadBalancer’ 24: # Java’s built-in classes don’t need to be quoted (for a String) 25: java_import java.util.concurrent.CountDownLatch 26: 27: # Convenience method for creating an Actor 28: def actorOf(&code) 29: Actors.actorOf(Class.new do 30: include UntypedActorFactory 31: define_method(:create) do |*args| 32: code[*args] 33: end 34: end.new) 35: end 36: 37: class Calculate; end 38: # Struct.new(...) creates an instance having the instance variables 39: # passed 40: class Work < Struct.new(:start, :nrOfElements); end 41: class Result < Struct.new(:value); end 42: 43: class Worker < UntypedActor 44: # needed by actorOf 45: def self.create(*args) 46: new *args 47: end 48: 49: # define the work 50: def calculatePiFor(start, nrOfElements) 51: # Here, we are using the identity 52: # Pi = 4 * sum_{k=0}^{infty} (-1)^k/(2 k + 1) 53: # We divide the work into chunks of nrOfElements 54: # Enumerable#inject may be a little foreign for Java programmers, but 55: # it can be thought of as a shorthand for looping and re-assigning 56: # the value of the block inside to the memo varialbe ("acc" in this case) 57: # "M...N" means a Range starting at M, ending *1 before* N. 58: ((start * nrOfElements)...((start + 1) * nrOfElements)).inject(0) do |acc,i| 59: acc + 4.0 * (1 - (i.modulo 2) * 2) / (2 * i + 1) 60: end 61: end 62: 63: # message handler 64: def onReceive(message) 65: # examining the class of an object is not very Ruby-esque.
  • 2. pi.rb Page 2 of 3 66: # in generatl, Rubyists prefer duck typing 67: if message.kind_of? Work 68: work = message 69: 70: # perform the work 71: result = calculatePiFor(work.start, work.nrOfElements) 72: 73: # reply with the result 74: context.replyUnsafe(Result.new(result)) 75: 76: else 77: raise IllegalArgumentException.new "Unknown message [#{message + b}]" 78: end 79: end 80: end 81: 82: class PiRouter < UntypedLoadBalancer 83: attr_reader :seq 84: 85: def initialize(workers) 86: super() # make sure the underlying Java proxy is properly initialized 87: @seq = CyclicIterator.new(workers) 88: end 89: end 90: 91: class Master < UntypedActor 92: def initialize(nrOfWorkers, nrOfMessages, nrOfElements, latch) 93: super() 94: @nrOfMessages, @nrOfElements, @latch = nrOfMessages, nrOfElements, latch 95: @nrOfResults, @pi = 0, 0.0 96: 97: # create the workers 98: workers = java.util.ArrayList.new 99: nrOfWorkers.times { workers << Actors.actorOf(Worker).start } 100: 101: # wrap them with a load-balancing router 102: @router = actorOf { PiRouter.new(workers) }.start 103: end 104: 105: # message handler 106: def onReceive(message) 107: if message.kind_of? Calculate 108: # schedule work 109: @nrOfMessages.times do |start| 110: @router.sendOneWay(Work.new(start, @nrOfElements), context) 111: end 112: 113: # send a PoisonPill to all workers telling them to shut down themselves 114: @router.sendOneWay(Routing::Broadcast.new(Actors.poisonPill)) 115: 116: # send a PoisonPill to the router, telling him to shut himself down 117: @router.sendOneWay Actors.poisonPill 118: elsif message.kind_of? Result # handle result from the worker 119: @pi += message.value 120: @nrOfResults += 1 121: context.stop if @nrOfResults == @nrOfMessages 122: else 123: raise IllegalArgumentException.new "Unknown message [#{message}]" 124: end 125: end 126: 127: def preStart 128: @start = java.lang.System.currentTimeMillis 129: end 130:
  • 3. pi.rb Page 3 of 3 131: def postStop 132: # tell the world that the calculation is complete 133: puts format("ntPi estimate: tt%sntCalculation time: t%s millis", 134: @pi, (java.lang.System.currentTimeMillis - @start)) 135: @latch.countDown 136: end 137: end 138: 139: 140: class Pi 141: def self.calculate(nrOfWorkers, nrOfElements, nrOfMessages) 142: # this latch is only plumbing to know when the calculation is completed 143: latch = CountDownLatch.new(1) 144: 145: # create the master 146: master = Actors.actorOf do 147: Master.new(nrOfWorkers.to_i, nrOfMessages.to_i, nrOfElements.to_i, latch) 148: end.start 149: master.sendOneWay(Calculate.new) # start the calculation 150: latch.await # wait for master to shut down 151: end 152: end 153: 154: # Ready to do the real work 155: if (ARGV.length < 3) 156: exit "Usage: $0 num_workers num_elements num_messages" 157: end 158: 159: Pi.calculate(*ARGV[0..2])