Class: Garcon::Future

Inherits:
IVar show all
Includes:
ExecutorOptions
Defined in:
lib/garcon/task/future.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from IVar

#add_observer, #fail, #set

Methods included from Observable

#add_observer, #count_observers, #delete_observer, #delete_observers, #with_observer

Methods included from Obligation

#complete?, #exception, #fulfilled?, #incomplete?, #pending?, #reason, #rejected?, #state, #unscheduled?, #value, #value!, #wait, #wait!

Methods included from Dereferenceable

#value

Constructor Details

#initialize(opts = {}) { ... } ⇒ Future

Create a new ‘Future` in the `:unscheduled` state.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :args (object, Array)

    Zero or more arguments to be passed the task block on execution.

Yields:

  • the asynchronous operation to perform

Raises:

  • (ArgumentError)

    if no block is given



42
43
44
45
46
47
48
49
# File 'lib/garcon/task/future.rb', line 42

def initialize(opts = {}, &block)
  raise ArgumentError.new('no block given') unless block_given?
  super(IVar::NO_VALUE, opts)
  @state    = :unscheduled
  @task     = block
  @executor = get_executor_from(opts) || Garcon.global_io_executor
  @args     = get_arguments_from(opts)
end

Class Method Details

.execute(opts = {}) { ... } ⇒ Future

Create a new ‘Future` object with the given block, execute it, and return the `:pending` object.

Examples:

future = Garcon::Future.execute{ sleep(1); 42 }
future.state #=> :pending

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :args (object, Array)

    Zero or more arguments to be passed the task block on execution.

Yields:

  • the asynchronous operation to perform.

Returns:

  • (Future)

    The newly created ‘Future` in the `:pending` state.

Raises:

  • (ArgumentError)

    if no block is given.



93
94
95
# File 'lib/garcon/task/future.rb', line 93

def self.execute(opts = {}, &block)
  Future.new(opts, &block).execute
end

Instance Method Details

#executeFuture

Execute an ‘:unscheduled` `Future`. Immediately sets the state to `:pending` and passes the block to a new thread/thread pool for eventual execution. Does nothing if the `Future` is in any state other than `:unscheduled`.

Examples:

Instance and execute in separate steps

future = Garcon::Future.new{ sleep(1); 42 }
future.state #=> :unscheduled
future.execute
future.state #=> :pending

Instance and execute in one line

future = Garcon::Future.new{ sleep(1); 42 }.execute
future.state #=> :pending

Returns:

  • (Future)

    a reference to ‘self`



67
68
69
70
71
72
# File 'lib/garcon/task/future.rb', line 67

def execute
  if compare_and_set_state(:pending, :unscheduled)
    @executor.post(@args){ work }
    self
  end
end