Class: QuackConcurrency::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/quack_concurrency/future.rb,
lib/quack_concurrency/future/canceled.rb,
lib/quack_concurrency/future/complete.rb

Defined Under Namespace

Classes: Canceled, Complete

Instance Method Summary collapse

Constructor Details

#initializeFuture

Creates a new QuackConcurrency::Future concurrency tool.



6
7
8
9
10
11
12
# File 'lib/quack_concurrency/future.rb', line 6

def initialize
  @waiter = Waiter.new
  @mutex = ::Mutex.new
  @value = nil
  @complete = false
  @exception = false
end

Instance Method Details

#cancel(exception = nil) ⇒ void

This method returns an undefined value.

Cancels the QuackConcurrency::Future. Calling #get will result in Canceled being raised. Same as ‘raise(Canceled.new)`.

Parameters:

  • exception (Exception) (defaults to: nil)

    custom ‘Exception` to set

Raises:



20
21
22
23
24
# File 'lib/quack_concurrency/future.rb', line 20

def cancel(exception = nil)
  exception ||= Canceled.new
  self.raise(exception)
  nil
end

#complete?Boolean

Checks if QuackConcurrency::Future has a value or was canceled.

Returns:

  • (Boolean)


28
29
30
# File 'lib/quack_concurrency/future.rb', line 28

def complete?
  @complete
end

#getObject

Note:

This method will block until the future has completed.

Gets the value of the QuackConcurrency::Future.

Returns:

Raises:



37
38
39
40
41
# File 'lib/quack_concurrency/future.rb', line 37

def get
  @waiter.wait
  Kernel.raise(@exception) if @exception
  @value
end

#raise(exception = nil) ⇒ void

This method returns an undefined value.

Cancels the QuackConcurrency::Future with a custom ‘Exception`.

Parameters:

  • exception (Exception) (defaults to: nil)

Raises:

  • (Complete)

    if the future has already completed



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/quack_concurrency/future.rb', line 47

def raise(exception = nil)
  unless exception == nil || exception.is_a?(Exception)
    Kernel.raise(ArgumentError, "'exception' must be nil or an instance of an Exception")
  end
  @mutex.synchronize do
    Kernel.raise(Complete) if @complete
    @complete = true
    @exception = exception || StandardError.new
    @waiter.resume_all_forever
  end
  nil
end

#set(new_value = nil) ⇒ void

This method returns an undefined value.

Sets the value of the QuackConcurrency::Future.

Parameters:

  • new_value (nil, Object) (defaults to: nil)

    value to assign to future

Raises:



64
65
66
67
68
69
70
71
72
# File 'lib/quack_concurrency/future.rb', line 64

def set(new_value = nil)
  @mutex.synchronize do
    Kernel.raise(Complete) if @complete
    @complete = true
    @value = new_value
    @waiter.resume_all_forever
  end
  nil
end