Class: Contender::FutureTask

Inherits:
Future
  • Object
show all
Defined in:
lib/contender/future_task.rb

Instance Method Summary collapse

Constructor Details

#initialize(callable) ⇒ undefined

Parameters:

  • callable (Object)


5
6
7
8
9
10
11
12
# File 'lib/contender/future_task.rb', line 5

def initialize(callable)
  @callable = callable

  @mutex = Mutex.new
  @condition = ConditionVariable.new

  @state = :ready
end

Instance Method Details

#callundefined

Returns:

  • (undefined)


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/contender/future_task.rb', line 75

def call
  @mutex.synchronize do
    return unless @state == :ready

    @state = :running
    @thread = Thread.current
  end

  begin
    @result = @callable.call
  rescue => exception
    @exception = exception
  end

  @mutex.synchronize do
    return unless @state == :running

    @state = :ran
    @condition.broadcast
  end
ensure
  @thread = nil
end

#cancel(should_interrupt) ⇒ Boolean

Returns True if this future was cancelled.

Parameters:

  • should_interrupt (Boolean)

Returns:

  • (Boolean)

    True if this future was cancelled



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/contender/future_task.rb', line 17

def cancel(should_interrupt)
  @mutex.synchronize do
    return false if done?

    if @state == :running
      return false unless should_interrupt
      @thread.raise InterruptError
    end

    @state = :cancelled
    @condition.broadcast
  end

  return true
end

#cancelled?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/contender/future_task.rb', line 35

def cancelled?
  @state == :cancelled
end

#done?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/contender/future_task.rb', line 41

def done?
  @state == :ran || @state == :cancelled
end

#result(timeout = nil) ⇒ Object

Returns The result of the future.

Parameters:

  • timeout (Integer) (defaults to: nil)

    Time to wait for the result

Returns:

  • (Object)

    The result of the future

Raises:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/contender/future_task.rb', line 51

def result(timeout = nil)
  @mutex.synchronize do
    unless done?
      @condition.wait @mutex, timeout

      unless done?
        raise TimeoutError, 'The operation did not complete before the given timeout'
      end
    end

    if @state == :cancelled
      raise CancellationError, 'Task was cancelled before it could be completed'
    end
  end

  if @exception
    raise ExecutionError, @exception
  end

  @result
end