Futures

tarcieri edited this page Sep 9, 2012 · 10 revisions

Futures allow you to request a computation and get the result later. There are two types of futures supported by Celluloid: method futures and block futures. Method futures work by invoking the future method on an actor. This method is analogous to the typical send method in that it takes a method name, followed by an arbitrary number of arguments, and a block. Let's invoke the report method from the charlie object from the basic usage example using a future:

>> future = charlie.future.report
 => #<Celluloid::Future:0x000001009759b8>
>> future.value
 => "Charlie Sheen is winning!"

The call to charlie.future immediately returns a Celluloid::Future object, regardless of how long it takes to execute the "report" method. To obtain the result of the call to "report", we call the Celluloid::Future#value method of the future object. This call will block until the value returned from the method call is available (i.e. the method has finished executing). If an exception occured during the method call, the call to future.value will reraise the same exception.

Futures also allow you to background the computation of any block:

>> future = Celluloid::Future.new { 2 + 2 }
 => #<Celluloid::Future:0x000001008425f0>
>> future.value
 => 4

However, using Celluloid::Future.new enqueues the future for execution on the internal threadpool. This threadpool does not limit the number of concurrently executing futures. If resource contention limits the acceptable number of concurrent futures then use the Actor future method.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.