forked from ruby-concurrency/concurrent-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
java_executor_service.rb
103 lines (84 loc) · 2.51 KB
/
java_executor_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
if Concurrent.on_jruby?
require 'concurrent/errors'
require 'concurrent/utility/engine'
require 'concurrent/executor/abstract_executor_service'
module Concurrent
# @!macro abstract_executor_service_public_api
# @!visibility private
class JavaExecutorService < AbstractExecutorService
java_import 'java.lang.Runnable'
FALLBACK_POLICY_CLASSES = {
abort: java.util.concurrent.ThreadPoolExecutor::AbortPolicy,
discard: java.util.concurrent.ThreadPoolExecutor::DiscardPolicy,
caller_runs: java.util.concurrent.ThreadPoolExecutor::CallerRunsPolicy
}.freeze
private_constant :FALLBACK_POLICY_CLASSES
def post(*args, &task)
raise ArgumentError.new('no block given') unless block_given?
return handle_fallback(*args, &task) unless running?
@executor.submit Job.new(args, task)
true
rescue Java::JavaUtilConcurrent::RejectedExecutionException
raise RejectedExecutionError
end
def wait_for_termination(timeout = nil)
if timeout.nil?
ok = @executor.awaitTermination(60, java.util.concurrent.TimeUnit::SECONDS) until ok
true
else
@executor.awaitTermination(1000 * timeout, java.util.concurrent.TimeUnit::MILLISECONDS)
end
end
def shutdown
synchronize do
@executor.shutdown
nil
end
end
def kill
synchronize do
@executor.shutdownNow
nil
end
end
private
def ns_running?
!(ns_shuttingdown? || ns_shutdown?)
end
def ns_shuttingdown?
if @executor.respond_to? :isTerminating
@executor.isTerminating
else
false
end
end
def ns_shutdown?
@executor.isShutdown || @executor.isTerminated
end
class Job
include Runnable
def initialize(args, block)
@args = args
@block = block
end
def run
@block.call(*@args)
end
end
private_constant :Job
end
class DaemonThreadFactory
# hide include from YARD
send :include, java.util.concurrent.ThreadFactory
def initialize(daemonize = true)
@daemonize = daemonize
end
def newThread(runnable)
thread = java.util.concurrent.Executors.defaultThreadFactory().newThread(runnable)
thread.setDaemon(@daemonize)
return thread
end
end
private_constant :DaemonThreadFactory
end
end