File tree Expand file tree Collapse file tree 2 files changed +27
-14
lines changed Expand file tree Collapse file tree 2 files changed +27
-14
lines changed Original file line number Diff line number Diff line change
1
+ require 'thread'
2
+
1
3
module Concurrent
2
4
3
5
# A simple utility class that executes a callable and returns and array of three elements:
4
6
# success - indicating if the callable has been executed without errors
5
7
# value - filled by the callable result if it has been executed without errors, nil otherwise
6
8
# reason - the error risen by the callable if it has been executed with errors, nil otherwise
7
9
class SafeTaskExecutor
8
- def initialize ( task )
10
+
11
+ def initialize ( task , opts = { } )
9
12
@task = task
13
+ @mutex = Mutex . new
14
+ @exception_class = opts . fetch ( :rescue_exception , false ) ? Exception : StandardError
10
15
end
11
16
12
17
# @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
22
20
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
24
30
25
- [ success , value , reason ]
31
+ [ success , value , reason ]
32
+ end
26
33
end
27
34
end
28
35
end
Original file line number Diff line number Diff line change @@ -26,6 +26,9 @@ module Concurrent
26
26
reason . should be_nil
27
27
end
28
28
29
+ it 'passes all arguments to #execute to the task'
30
+
31
+ it 'protectes #execute with a mutex'
29
32
end
30
33
31
34
context 'failing execution' do
@@ -49,9 +52,12 @@ module Concurrent
49
52
reason . message . should eq 'an error'
50
53
end
51
54
52
- end
55
+ it 'rescues Exception when :rescue_exception is true'
53
56
54
- end
57
+ it 'rescues StandardError when :rescue_exception is false'
55
58
59
+ it 'rescues StandardError by default'
60
+ end
61
+ end
56
62
end
57
63
end
You can’t perform that action at this time.
0 commit comments