Class: VCAP::Concurrency::Promise
- Inherits:
-
Object
- Object
- VCAP::Concurrency::Promise
- 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
-
#deliver(result = nil) ⇒ nil
Fulfills the promise successfully.
-
#fail(exception) ⇒ nil
Fulfills the promise unsuccessfully.
-
#initialize ⇒ Promise
constructor
A new instance of Promise.
-
#resolve(timeout_secs = nil) ⇒ Object
Waits for the promise to be fulfilled.
Constructor Details
#initialize ⇒ Promise
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.
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().
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().
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 |