Class: Tribe::Future

Inherits:
Object
  • Object
show all
Defined in:
lib/tribe/future.rb

Instance Method Summary collapse

Constructor Details

#initializeFuture

Returns a new instance of Future.



3
4
5
6
7
8
9
10
11
12
# File 'lib/tribe/future.rb', line 3

def initialize
  @state = :initialized
  @mutex = Mutex.new
  @condition = ConditionVariable.new
  @result = nil
  @success_callback = nil
  @failure_callback = nil

  return nil
end

Instance Method Details

#failure(&block) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/tribe/future.rb', line 83

def failure(&block)
  @mutex.synchronize do
    case @state
    when :initialized
      @failure_callback = block
    when :finished
      yield(@result) if @result.is_a?(Exception)
    else
      raise Tribe::FutureError.new('Invalid state.')
    end

    return nil
  end
end

#failure?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/tribe/future.rb', line 64

def failure?
  return !success?
end

#finished?Boolean

Returns:

  • (Boolean)


14
15
16
17
18
# File 'lib/tribe/future.rb', line 14

def finished?
  @mutex.synchronize do
    return @state == :finished
  end
end

#resultObject



38
39
40
41
42
43
44
# File 'lib/tribe/future.rb', line 38

def result
  @mutex.synchronize do
    raise Tribe::FutureError.new('Result must be set first.') unless @state == :finished

    return @result
  end
end

#result=(val) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tribe/future.rb', line 20

def result=(val)
  @mutex.synchronize do
    raise Tribe::FutureError.new('Result must only be set once.') unless @state == :initialized

    @result = val
    @state = :finished
    @condition.signal

    if val.is_a?(Exception)
      @failure_callback.call(val) if @failure_callback
    else
      @success_callback.call(val) if @success_callback
    end

    return nil
  end
end

#success(&block) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/tribe/future.rb', line 68

def success(&block)
  @mutex.synchronize do
    case @state
    when :initialized
      @success_callback = block
    when :finished
      yield(@result) unless @result.is_a?(Exception)
    else
      raise Tribe::FutureError.new('Invalid state.')
    end

    return nil
  end
end

#success?Boolean

Returns:

  • (Boolean)


56
57
58
59
60
61
62
# File 'lib/tribe/future.rb', line 56

def success?
  @mutex.synchronize do
    raise Tribe::FutureError.new('Result must be set first.') unless @state == :finished

    return !@result.is_a?(Exception)
  end
end

#waitObject



46
47
48
49
50
51
52
53
54
# File 'lib/tribe/future.rb', line 46

def wait
  @mutex.synchronize do
    return if @state == :finished

    @condition.wait(@mutex)

    return nil
  end
end