Class: VCAP::Concurrency::Promise

Inherits:
Object
  • Object
show all
Defined in:
lib/vcap/concurrency/promise.rb

Overview

A promise represents the intent to complete a unit of work at some point in the future.

Instance Method Summary collapse

Constructor Details

#initializePromise

Returns a new instance of Promise.



13
14
15
16
17
18
19
# File 'lib/vcap/concurrency/promise.rb', line 13

def initialize
  @lock   = Mutex.new
  @cond   = ConditionVariable.new
  @done   = false
  @result = nil
  @error  = nil
end

Instance Method Details

#deliver(result = nil) ⇒ nil

Fulfills the promise successfully. Anyone blocking on the result will be notified immediately.

Parameters:

  • result (Object) (defaults to: nil)

    The result of the associated computation.

Returns:

  • (nil)


27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/vcap/concurrency/promise.rb', line 27

def deliver(result = nil)
  @lock.synchronize do
    assert_not_done

    @result = result
    @done = true

    @cond.broadcast
  end

  nil
end

#fail(exception) ⇒ nil

Fulfills the promise unsuccessfully. Anyone blocking on the result will be notified immediately.

NB: The supplied exception will be re raised in the caller of #resolve().

Parameters:

  • The (Exception)

    error that occurred while fulfilling the promise.

Returns:

  • (nil)


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/vcap/concurrency/promise.rb', line 48

def fail(exception)
  @lock.synchronize do
    assert_not_done

    @error = exception
    @done = true

    @cond.broadcast
  end

  nil
end

#resolve(timeout_secs = nil) ⇒ Object

Waits for the promise to be fulfilled. Blocks the calling thread if the promise has not been fulfilled, otherwise it returns immediately.

NB: If the promise failed to be fulfilled, the error that occurred while

fulfilling it will be raised here.

value before proceeding. An exception will be raised if the promise hasn’t been fulfilled when the timeout occurs.

fulfilled after timeout_secs seconds since calling resolve().

Parameters:

  • timeout_secs (Integer) (defaults to: nil)

    If supplied, wait for no longer than this

Returns:

  • (Object)

    The result of the associated computation.

Raises:



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/vcap/concurrency/promise.rb', line 75

def resolve(timeout_secs = nil)
  @lock.synchronize do
    @cond.wait(@lock, timeout_secs) unless @done

    if !@done
      emsg = "Timed out waiting on result after #{timeout_secs}s."
      raise VCAP::Concurrency::TimeoutError.new(emsg)
    end

    if @error
      raise @error
    else
      @result
    end
  end
end