Skip to content

Commit 8bcc8ee

Browse files
committed
Added Mutex and :rescue_exception option to SafeTaskExecutor.
1 parent e03382d commit 8bcc8ee

File tree

2 files changed

+27
-14
lines changed

2 files changed

+27
-14
lines changed
Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
1+
require 'thread'
2+
13
module Concurrent
24

35
# A simple utility class that executes a callable and returns and array of three elements:
46
# success - indicating if the callable has been executed without errors
57
# value - filled by the callable result if it has been executed without errors, nil otherwise
68
# reason - the error risen by the callable if it has been executed with errors, nil otherwise
79
class SafeTaskExecutor
8-
def initialize(task)
10+
11+
def initialize(task, opts = {})
912
@task = task
13+
@mutex = Mutex.new
14+
@exception_class = opts.fetch(:rescue_exception, false) ? Exception : StandardError
1015
end
1116

1217
# @return [Array]
13-
def execute
14-
success = false
15-
value = reason = nil
16-
17-
begin
18-
value = @task.call
19-
success = true
20-
rescue => ex
21-
reason = ex
18+
def execute(*args)
19+
@mutex.synchronize do
2220
success = false
23-
end
21+
value = reason = nil
22+
23+
begin
24+
value = @task.call(*args)
25+
success = true
26+
rescue @exception_class => ex
27+
reason = ex
28+
success = false
29+
end
2430

25-
[success, value, reason]
31+
[success, value, reason]
32+
end
2633
end
2734
end
2835
end

spec/concurrent/executor/safe_task_executor_spec.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ module Concurrent
2626
reason.should be_nil
2727
end
2828

29+
it 'passes all arguments to #execute to the task'
30+
31+
it 'protectes #execute with a mutex'
2932
end
3033

3134
context 'failing execution' do
@@ -49,9 +52,12 @@ module Concurrent
4952
reason.message.should eq 'an error'
5053
end
5154

52-
end
55+
it 'rescues Exception when :rescue_exception is true'
5356

54-
end
57+
it 'rescues StandardError when :rescue_exception is false'
5558

59+
it 'rescues StandardError by default'
60+
end
61+
end
5662
end
5763
end

0 commit comments

Comments
 (0)