o-concurrent-ruby 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +542 -0
  3. data/Gemfile +37 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +404 -0
  6. data/Rakefile +307 -0
  7. data/ext/concurrent-ruby/ConcurrentRubyService.java +17 -0
  8. data/ext/concurrent-ruby/com/concurrent_ruby/ext/AtomicReferenceLibrary.java +175 -0
  9. data/ext/concurrent-ruby/com/concurrent_ruby/ext/JRubyMapBackendLibrary.java +248 -0
  10. data/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicBooleanLibrary.java +93 -0
  11. data/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaAtomicFixnumLibrary.java +113 -0
  12. data/ext/concurrent-ruby/com/concurrent_ruby/ext/JavaSemaphoreLibrary.java +189 -0
  13. data/ext/concurrent-ruby/com/concurrent_ruby/ext/SynchronizationLibrary.java +307 -0
  14. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMap.java +31 -0
  15. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/ConcurrentHashMapV8.java +3863 -0
  16. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/LongAdder.java +203 -0
  17. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/Striped64.java +342 -0
  18. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/ConcurrentHashMapV8.java +3800 -0
  19. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/LongAdder.java +204 -0
  20. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166e/nounsafe/Striped64.java +291 -0
  21. data/ext/concurrent-ruby/com/concurrent_ruby/ext/jsr166y/ThreadLocalRandom.java +199 -0
  22. data/lib/concurrent-ruby/concurrent/agent.rb +587 -0
  23. data/lib/concurrent-ruby/concurrent/array.rb +66 -0
  24. data/lib/concurrent-ruby/concurrent/async.rb +449 -0
  25. data/lib/concurrent-ruby/concurrent/atom.rb +222 -0
  26. data/lib/concurrent-ruby/concurrent/atomic/abstract_thread_local_var.rb +66 -0
  27. data/lib/concurrent-ruby/concurrent/atomic/atomic_boolean.rb +126 -0
  28. data/lib/concurrent-ruby/concurrent/atomic/atomic_fixnum.rb +143 -0
  29. data/lib/concurrent-ruby/concurrent/atomic/atomic_markable_reference.rb +164 -0
  30. data/lib/concurrent-ruby/concurrent/atomic/atomic_reference.rb +205 -0
  31. data/lib/concurrent-ruby/concurrent/atomic/count_down_latch.rb +100 -0
  32. data/lib/concurrent-ruby/concurrent/atomic/cyclic_barrier.rb +128 -0
  33. data/lib/concurrent-ruby/concurrent/atomic/event.rb +109 -0
  34. data/lib/concurrent-ruby/concurrent/atomic/java_count_down_latch.rb +42 -0
  35. data/lib/concurrent-ruby/concurrent/atomic/java_thread_local_var.rb +37 -0
  36. data/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_boolean.rb +62 -0
  37. data/lib/concurrent-ruby/concurrent/atomic/mutex_atomic_fixnum.rb +75 -0
  38. data/lib/concurrent-ruby/concurrent/atomic/mutex_count_down_latch.rb +44 -0
  39. data/lib/concurrent-ruby/concurrent/atomic/mutex_semaphore.rb +131 -0
  40. data/lib/concurrent-ruby/concurrent/atomic/read_write_lock.rb +254 -0
  41. data/lib/concurrent-ruby/concurrent/atomic/reentrant_read_write_lock.rb +377 -0
  42. data/lib/concurrent-ruby/concurrent/atomic/ruby_thread_local_var.rb +181 -0
  43. data/lib/concurrent-ruby/concurrent/atomic/semaphore.rb +166 -0
  44. data/lib/concurrent-ruby/concurrent/atomic/thread_local_var.rb +104 -0
  45. data/lib/concurrent-ruby/concurrent/atomic_reference/mutex_atomic.rb +56 -0
  46. data/lib/concurrent-ruby/concurrent/atomic_reference/numeric_cas_wrapper.rb +28 -0
  47. data/lib/concurrent-ruby/concurrent/atomics.rb +10 -0
  48. data/lib/concurrent-ruby/concurrent/collection/copy_on_notify_observer_set.rb +107 -0
  49. data/lib/concurrent-ruby/concurrent/collection/copy_on_write_observer_set.rb +111 -0
  50. data/lib/concurrent-ruby/concurrent/collection/java_non_concurrent_priority_queue.rb +84 -0
  51. data/lib/concurrent-ruby/concurrent/collection/lock_free_stack.rb +158 -0
  52. data/lib/concurrent-ruby/concurrent/collection/map/atomic_reference_map_backend.rb +927 -0
  53. data/lib/concurrent-ruby/concurrent/collection/map/mri_map_backend.rb +66 -0
  54. data/lib/concurrent-ruby/concurrent/collection/map/non_concurrent_map_backend.rb +140 -0
  55. data/lib/concurrent-ruby/concurrent/collection/map/synchronized_map_backend.rb +82 -0
  56. data/lib/concurrent-ruby/concurrent/collection/map/truffleruby_map_backend.rb +14 -0
  57. data/lib/concurrent-ruby/concurrent/collection/non_concurrent_priority_queue.rb +143 -0
  58. data/lib/concurrent-ruby/concurrent/collection/ruby_non_concurrent_priority_queue.rb +160 -0
  59. data/lib/concurrent-ruby/concurrent/concern/deprecation.rb +34 -0
  60. data/lib/concurrent-ruby/concurrent/concern/dereferenceable.rb +73 -0
  61. data/lib/concurrent-ruby/concurrent/concern/logging.rb +32 -0
  62. data/lib/concurrent-ruby/concurrent/concern/obligation.rb +220 -0
  63. data/lib/concurrent-ruby/concurrent/concern/observable.rb +110 -0
  64. data/lib/concurrent-ruby/concurrent/configuration.rb +188 -0
  65. data/lib/concurrent-ruby/concurrent/constants.rb +8 -0
  66. data/lib/concurrent-ruby/concurrent/dataflow.rb +81 -0
  67. data/lib/concurrent-ruby/concurrent/delay.rb +199 -0
  68. data/lib/concurrent-ruby/concurrent/errors.rb +69 -0
  69. data/lib/concurrent-ruby/concurrent/exchanger.rb +352 -0
  70. data/lib/concurrent-ruby/concurrent/executor/abstract_executor_service.rb +131 -0
  71. data/lib/concurrent-ruby/concurrent/executor/cached_thread_pool.rb +62 -0
  72. data/lib/concurrent-ruby/concurrent/executor/executor_service.rb +185 -0
  73. data/lib/concurrent-ruby/concurrent/executor/fixed_thread_pool.rb +220 -0
  74. data/lib/concurrent-ruby/concurrent/executor/immediate_executor.rb +66 -0
  75. data/lib/concurrent-ruby/concurrent/executor/indirect_immediate_executor.rb +44 -0
  76. data/lib/concurrent-ruby/concurrent/executor/java_executor_service.rb +103 -0
  77. data/lib/concurrent-ruby/concurrent/executor/java_single_thread_executor.rb +30 -0
  78. data/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb +140 -0
  79. data/lib/concurrent-ruby/concurrent/executor/ruby_executor_service.rb +82 -0
  80. data/lib/concurrent-ruby/concurrent/executor/ruby_single_thread_executor.rb +21 -0
  81. data/lib/concurrent-ruby/concurrent/executor/ruby_thread_pool_executor.rb +368 -0
  82. data/lib/concurrent-ruby/concurrent/executor/safe_task_executor.rb +35 -0
  83. data/lib/concurrent-ruby/concurrent/executor/serial_executor_service.rb +34 -0
  84. data/lib/concurrent-ruby/concurrent/executor/serialized_execution.rb +107 -0
  85. data/lib/concurrent-ruby/concurrent/executor/serialized_execution_delegator.rb +28 -0
  86. data/lib/concurrent-ruby/concurrent/executor/simple_executor_service.rb +100 -0
  87. data/lib/concurrent-ruby/concurrent/executor/single_thread_executor.rb +57 -0
  88. data/lib/concurrent-ruby/concurrent/executor/thread_pool_executor.rb +88 -0
  89. data/lib/concurrent-ruby/concurrent/executor/timer_set.rb +172 -0
  90. data/lib/concurrent-ruby/concurrent/executors.rb +20 -0
  91. data/lib/concurrent-ruby/concurrent/future.rb +141 -0
  92. data/lib/concurrent-ruby/concurrent/hash.rb +59 -0
  93. data/lib/concurrent-ruby/concurrent/immutable_struct.rb +101 -0
  94. data/lib/concurrent-ruby/concurrent/ivar.rb +207 -0
  95. data/lib/concurrent-ruby/concurrent/map.rb +346 -0
  96. data/lib/concurrent-ruby/concurrent/maybe.rb +229 -0
  97. data/lib/concurrent-ruby/concurrent/mutable_struct.rb +239 -0
  98. data/lib/concurrent-ruby/concurrent/mvar.rb +242 -0
  99. data/lib/concurrent-ruby/concurrent/options.rb +42 -0
  100. data/lib/concurrent-ruby/concurrent/promise.rb +580 -0
  101. data/lib/concurrent-ruby/concurrent/promises.rb +2167 -0
  102. data/lib/concurrent-ruby/concurrent/re_include.rb +58 -0
  103. data/lib/concurrent-ruby/concurrent/scheduled_task.rb +331 -0
  104. data/lib/concurrent-ruby/concurrent/set.rb +74 -0
  105. data/lib/concurrent-ruby/concurrent/settable_struct.rb +139 -0
  106. data/lib/concurrent-ruby/concurrent/synchronization/abstract_lockable_object.rb +98 -0
  107. data/lib/concurrent-ruby/concurrent/synchronization/abstract_object.rb +24 -0
  108. data/lib/concurrent-ruby/concurrent/synchronization/abstract_struct.rb +171 -0
  109. data/lib/concurrent-ruby/concurrent/synchronization/condition.rb +60 -0
  110. data/lib/concurrent-ruby/concurrent/synchronization/jruby_lockable_object.rb +13 -0
  111. data/lib/concurrent-ruby/concurrent/synchronization/jruby_object.rb +45 -0
  112. data/lib/concurrent-ruby/concurrent/synchronization/lock.rb +36 -0
  113. data/lib/concurrent-ruby/concurrent/synchronization/lockable_object.rb +72 -0
  114. data/lib/concurrent-ruby/concurrent/synchronization/mri_object.rb +44 -0
  115. data/lib/concurrent-ruby/concurrent/synchronization/mutex_lockable_object.rb +88 -0
  116. data/lib/concurrent-ruby/concurrent/synchronization/object.rb +183 -0
  117. data/lib/concurrent-ruby/concurrent/synchronization/rbx_lockable_object.rb +71 -0
  118. data/lib/concurrent-ruby/concurrent/synchronization/rbx_object.rb +49 -0
  119. data/lib/concurrent-ruby/concurrent/synchronization/truffleruby_object.rb +47 -0
  120. data/lib/concurrent-ruby/concurrent/synchronization/volatile.rb +36 -0
  121. data/lib/concurrent-ruby/concurrent/synchronization.rb +30 -0
  122. data/lib/concurrent-ruby/concurrent/thread_safe/synchronized_delegator.rb +50 -0
  123. data/lib/concurrent-ruby/concurrent/thread_safe/util/adder.rb +74 -0
  124. data/lib/concurrent-ruby/concurrent/thread_safe/util/cheap_lockable.rb +118 -0
  125. data/lib/concurrent-ruby/concurrent/thread_safe/util/data_structures.rb +88 -0
  126. data/lib/concurrent-ruby/concurrent/thread_safe/util/power_of_two_tuple.rb +38 -0
  127. data/lib/concurrent-ruby/concurrent/thread_safe/util/striped64.rb +246 -0
  128. data/lib/concurrent-ruby/concurrent/thread_safe/util/volatile.rb +75 -0
  129. data/lib/concurrent-ruby/concurrent/thread_safe/util/xor_shift_random.rb +50 -0
  130. data/lib/concurrent-ruby/concurrent/thread_safe/util.rb +16 -0
  131. data/lib/concurrent-ruby/concurrent/timer_task.rb +311 -0
  132. data/lib/concurrent-ruby/concurrent/tuple.rb +86 -0
  133. data/lib/concurrent-ruby/concurrent/tvar.rb +221 -0
  134. data/lib/concurrent-ruby/concurrent/utility/engine.rb +56 -0
  135. data/lib/concurrent-ruby/concurrent/utility/monotonic_time.rb +90 -0
  136. data/lib/concurrent-ruby/concurrent/utility/native_extension_loader.rb +79 -0
  137. data/lib/concurrent-ruby/concurrent/utility/native_integer.rb +53 -0
  138. data/lib/concurrent-ruby/concurrent/utility/processor_counter.rb +130 -0
  139. data/lib/concurrent-ruby/concurrent/version.rb +3 -0
  140. data/lib/concurrent-ruby/concurrent-ruby.rb +5 -0
  141. data/lib/concurrent-ruby/concurrent.rb +134 -0
  142. metadata +192 -0
@@ -0,0 +1,58 @@
1
+ module Concurrent
2
+
3
+ # Methods form module A included to a module B, which is already included into class C,
4
+ # will not be visible in the C class. If this module is extended to B then A's methods
5
+ # are correctly made visible to C.
6
+ #
7
+ # @example
8
+ # module A
9
+ # def a
10
+ # :a
11
+ # end
12
+ # end
13
+ #
14
+ # module B1
15
+ # end
16
+ #
17
+ # class C1
18
+ # include B1
19
+ # end
20
+ #
21
+ # module B2
22
+ # extend Concurrent::ReInclude
23
+ # end
24
+ #
25
+ # class C2
26
+ # include B2
27
+ # end
28
+ #
29
+ # B1.send :include, A
30
+ # B2.send :include, A
31
+ #
32
+ # C1.new.respond_to? :a # => false
33
+ # C2.new.respond_to? :a # => true
34
+ module ReInclude
35
+ # @!visibility private
36
+ def included(base)
37
+ (@re_include_to_bases ||= []) << [:include, base]
38
+ super(base)
39
+ end
40
+
41
+ # @!visibility private
42
+ def extended(base)
43
+ (@re_include_to_bases ||= []) << [:extend, base]
44
+ super(base)
45
+ end
46
+
47
+ # @!visibility private
48
+ def include(*modules)
49
+ result = super(*modules)
50
+ modules.reverse.each do |module_being_included|
51
+ (@re_include_to_bases ||= []).each do |method, mod|
52
+ mod.send method, module_being_included
53
+ end
54
+ end
55
+ result
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,331 @@
1
+ require 'concurrent/constants'
2
+ require 'concurrent/errors'
3
+ require 'concurrent/configuration'
4
+ require 'concurrent/ivar'
5
+ require 'concurrent/collection/copy_on_notify_observer_set'
6
+ require 'concurrent/utility/monotonic_time'
7
+
8
+ require 'concurrent/options'
9
+
10
+ module Concurrent
11
+
12
+ # `ScheduledTask` is a close relative of `Concurrent::Future` but with one
13
+ # important difference: A `Future` is set to execute as soon as possible
14
+ # whereas a `ScheduledTask` is set to execute after a specified delay. This
15
+ # implementation is loosely based on Java's
16
+ # [ScheduledExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html).
17
+ # It is a more feature-rich variant of {Concurrent.timer}.
18
+ #
19
+ # The *intended* schedule time of task execution is set on object construction
20
+ # with the `delay` argument. The delay is a numeric (floating point or integer)
21
+ # representing a number of seconds in the future. Any other value or a numeric
22
+ # equal to or less than zero will result in an exception. The *actual* schedule
23
+ # time of task execution is set when the `execute` method is called.
24
+ #
25
+ # The constructor can also be given zero or more processing options. Currently
26
+ # the only supported options are those recognized by the
27
+ # [Dereferenceable](Dereferenceable) module.
28
+ #
29
+ # The final constructor argument is a block representing the task to be performed.
30
+ # If no block is given an `ArgumentError` will be raised.
31
+ #
32
+ # **States**
33
+ #
34
+ # `ScheduledTask` mixes in the [Obligation](Obligation) module thus giving it
35
+ # "future" behavior. This includes the expected lifecycle states. `ScheduledTask`
36
+ # has one additional state, however. While the task (block) is being executed the
37
+ # state of the object will be `:processing`. This additional state is necessary
38
+ # because it has implications for task cancellation.
39
+ #
40
+ # **Cancellation**
41
+ #
42
+ # A `:pending` task can be cancelled using the `#cancel` method. A task in any
43
+ # other state, including `:processing`, cannot be cancelled. The `#cancel`
44
+ # method returns a boolean indicating the success of the cancellation attempt.
45
+ # A cancelled `ScheduledTask` cannot be restarted. It is immutable.
46
+ #
47
+ # **Obligation and Observation**
48
+ #
49
+ # The result of a `ScheduledTask` can be obtained either synchronously or
50
+ # asynchronously. `ScheduledTask` mixes in both the [Obligation](Obligation)
51
+ # module and the
52
+ # [Observable](http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html)
53
+ # module from the Ruby standard library. With one exception `ScheduledTask`
54
+ # behaves identically to [Future](Observable) with regard to these modules.
55
+ #
56
+ # @!macro copy_options
57
+ #
58
+ # @example Basic usage
59
+ #
60
+ # require 'concurrent'
61
+ # require 'csv'
62
+ # require 'open-uri'
63
+ #
64
+ # class Ticker
65
+ # def get_year_end_closing(symbol, year, api_key)
66
+ # uri = "https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=#{symbol}&apikey=#{api_key}&datatype=csv"
67
+ # data = []
68
+ # csv = URI.parse(uri).read
69
+ # if csv.include?('call frequency')
70
+ # return :rate_limit_exceeded
71
+ # end
72
+ # CSV.parse(csv, headers: true) do |row|
73
+ # data << row['close'].to_f if row['timestamp'].include?(year.to_s)
74
+ # end
75
+ # year_end = data.first
76
+ # year_end
77
+ # rescue => e
78
+ # p e
79
+ # end
80
+ # end
81
+ #
82
+ # api_key = ENV['ALPHAVANTAGE_KEY']
83
+ # abort(error_message) unless api_key
84
+ #
85
+ # # Future
86
+ # price = Concurrent::Future.execute{ Ticker.new.get_year_end_closing('TWTR', 2013, api_key) }
87
+ # price.state #=> :pending
88
+ # price.pending? #=> true
89
+ # price.value(0) #=> nil (does not block)
90
+ #
91
+ # sleep(1) # do other stuff
92
+ #
93
+ # price.value #=> 63.65 (after blocking if necessary)
94
+ # price.state #=> :fulfilled
95
+ # price.fulfilled? #=> true
96
+ # price.value #=> 63.65
97
+ #
98
+ # @example Successful task execution
99
+ #
100
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
101
+ # task.state #=> :unscheduled
102
+ # task.execute
103
+ # task.state #=> pending
104
+ #
105
+ # # wait for it...
106
+ # sleep(3)
107
+ #
108
+ # task.unscheduled? #=> false
109
+ # task.pending? #=> false
110
+ # task.fulfilled? #=> true
111
+ # task.rejected? #=> false
112
+ # task.value #=> 'What does the fox say?'
113
+ #
114
+ # @example One line creation and execution
115
+ #
116
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }.execute
117
+ # task.state #=> pending
118
+ #
119
+ # task = Concurrent::ScheduledTask.execute(2){ 'What do you get when you multiply 6 by 9?' }
120
+ # task.state #=> pending
121
+ #
122
+ # @example Failed task execution
123
+ #
124
+ # task = Concurrent::ScheduledTask.execute(2){ raise StandardError.new('Call me maybe?') }
125
+ # task.pending? #=> true
126
+ #
127
+ # # wait for it...
128
+ # sleep(3)
129
+ #
130
+ # task.unscheduled? #=> false
131
+ # task.pending? #=> false
132
+ # task.fulfilled? #=> false
133
+ # task.rejected? #=> true
134
+ # task.value #=> nil
135
+ # task.reason #=> #<StandardError: Call me maybe?>
136
+ #
137
+ # @example Task execution with observation
138
+ #
139
+ # observer = Class.new{
140
+ # def update(time, value, reason)
141
+ # puts "The task completed at #{time} with value '#{value}'"
142
+ # end
143
+ # }.new
144
+ #
145
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
146
+ # task.add_observer(observer)
147
+ # task.execute
148
+ # task.pending? #=> true
149
+ #
150
+ # # wait for it...
151
+ # sleep(3)
152
+ #
153
+ # #>> The task completed at 2013-11-07 12:26:09 -0500 with value 'What does the fox say?'
154
+ #
155
+ # @!macro monotonic_clock_warning
156
+ #
157
+ # @see Concurrent.timer
158
+ class ScheduledTask < IVar
159
+ include Comparable
160
+
161
+ # The executor on which to execute the task.
162
+ # @!visibility private
163
+ attr_reader :executor
164
+
165
+ # Schedule a task for execution at a specified future time.
166
+ #
167
+ # @param [Float] delay the number of seconds to wait for before executing the task
168
+ #
169
+ # @yield the task to be performed
170
+ #
171
+ # @!macro executor_and_deref_options
172
+ #
173
+ # @option opts [object, Array] :args zero or more arguments to be passed the task
174
+ # block on execution
175
+ #
176
+ # @raise [ArgumentError] When no block is given
177
+ # @raise [ArgumentError] When given a time that is in the past
178
+ def initialize(delay, opts = {}, &task)
179
+ raise ArgumentError.new('no block given') unless block_given?
180
+ raise ArgumentError.new('seconds must be greater than zero') if delay.to_f < 0.0
181
+
182
+ super(NULL, opts, &nil)
183
+
184
+ synchronize do
185
+ ns_set_state(:unscheduled)
186
+ @parent = opts.fetch(:timer_set, Concurrent.global_timer_set)
187
+ @args = get_arguments_from(opts)
188
+ @delay = delay.to_f
189
+ @task = task
190
+ @time = nil
191
+ @executor = Options.executor_from_options(opts) || Concurrent.global_io_executor
192
+ self.observers = Collection::CopyOnNotifyObserverSet.new
193
+ end
194
+ end
195
+
196
+ # The `delay` value given at instanciation.
197
+ #
198
+ # @return [Float] the initial delay.
199
+ def initial_delay
200
+ synchronize { @delay }
201
+ end
202
+
203
+ # The monotonic time at which the the task is scheduled to be executed.
204
+ #
205
+ # @return [Float] the schedule time or nil if `unscheduled`
206
+ def schedule_time
207
+ synchronize { @time }
208
+ end
209
+
210
+ # Comparator which orders by schedule time.
211
+ #
212
+ # @!visibility private
213
+ def <=>(other)
214
+ schedule_time <=> other.schedule_time
215
+ end
216
+
217
+ # Has the task been cancelled?
218
+ #
219
+ # @return [Boolean] true if the task is in the given state else false
220
+ def cancelled?
221
+ synchronize { ns_check_state?(:cancelled) }
222
+ end
223
+
224
+ # In the task execution in progress?
225
+ #
226
+ # @return [Boolean] true if the task is in the given state else false
227
+ def processing?
228
+ synchronize { ns_check_state?(:processing) }
229
+ end
230
+
231
+ # Cancel this task and prevent it from executing. A task can only be
232
+ # cancelled if it is pending or unscheduled.
233
+ #
234
+ # @return [Boolean] true if successfully cancelled else false
235
+ def cancel
236
+ if compare_and_set_state(:cancelled, :pending, :unscheduled)
237
+ complete(false, nil, CancelledOperationError.new)
238
+ # To avoid deadlocks this call must occur outside of #synchronize
239
+ # Changing the state above should prevent redundant calls
240
+ @parent.send(:remove_task, self)
241
+ else
242
+ false
243
+ end
244
+ end
245
+
246
+ # Reschedule the task using the original delay and the current time.
247
+ # A task can only be reset while it is `:pending`.
248
+ #
249
+ # @return [Boolean] true if successfully rescheduled else false
250
+ def reset
251
+ synchronize{ ns_reschedule(@delay) }
252
+ end
253
+
254
+ # Reschedule the task using the given delay and the current time.
255
+ # A task can only be reset while it is `:pending`.
256
+ #
257
+ # @param [Float] delay the number of seconds to wait for before executing the task
258
+ #
259
+ # @return [Boolean] true if successfully rescheduled else false
260
+ #
261
+ # @raise [ArgumentError] When given a time that is in the past
262
+ def reschedule(delay)
263
+ delay = delay.to_f
264
+ raise ArgumentError.new('seconds must be greater than zero') if delay < 0.0
265
+ synchronize{ ns_reschedule(delay) }
266
+ end
267
+
268
+ # Execute an `:unscheduled` `ScheduledTask`. Immediately sets the state to `:pending`
269
+ # and starts counting down toward execution. Does nothing if the `ScheduledTask` is
270
+ # in any state other than `:unscheduled`.
271
+ #
272
+ # @return [ScheduledTask] a reference to `self`
273
+ def execute
274
+ if compare_and_set_state(:pending, :unscheduled)
275
+ synchronize{ ns_schedule(@delay) }
276
+ end
277
+ self
278
+ end
279
+
280
+ # Create a new `ScheduledTask` object with the given block, execute it, and return the
281
+ # `:pending` object.
282
+ #
283
+ # @param [Float] delay the number of seconds to wait for before executing the task
284
+ #
285
+ # @!macro executor_and_deref_options
286
+ #
287
+ # @return [ScheduledTask] the newly created `ScheduledTask` in the `:pending` state
288
+ #
289
+ # @raise [ArgumentError] if no block is given
290
+ def self.execute(delay, opts = {}, &task)
291
+ new(delay, opts, &task).execute
292
+ end
293
+
294
+ # Execute the task.
295
+ #
296
+ # @!visibility private
297
+ def process_task
298
+ safe_execute(@task, @args)
299
+ end
300
+
301
+ protected :set, :try_set, :fail, :complete
302
+
303
+ protected
304
+
305
+ # Schedule the task using the given delay and the current time.
306
+ #
307
+ # @param [Float] delay the number of seconds to wait for before executing the task
308
+ #
309
+ # @return [Boolean] true if successfully rescheduled else false
310
+ #
311
+ # @!visibility private
312
+ def ns_schedule(delay)
313
+ @delay = delay
314
+ @time = Concurrent.monotonic_time + @delay
315
+ @parent.send(:post_task, self)
316
+ end
317
+
318
+ # Reschedule the task using the given delay and the current time.
319
+ # A task can only be reset while it is `:pending`.
320
+ #
321
+ # @param [Float] delay the number of seconds to wait for before executing the task
322
+ #
323
+ # @return [Boolean] true if successfully rescheduled else false
324
+ #
325
+ # @!visibility private
326
+ def ns_reschedule(delay)
327
+ return false unless ns_check_state?(:pending)
328
+ @parent.send(:remove_task, self) && ns_schedule(delay)
329
+ end
330
+ end
331
+ end
@@ -0,0 +1,74 @@
1
+ require 'concurrent/utility/engine'
2
+ require 'concurrent/thread_safe/util'
3
+ require 'set'
4
+
5
+ module Concurrent
6
+
7
+ # @!macro concurrent_set
8
+ #
9
+ # A thread-safe subclass of Set. This version locks against the object
10
+ # itself for every method call, ensuring only one thread can be reading
11
+ # or writing at a time. This includes iteration methods like `#each`.
12
+ #
13
+ # @note `a += b` is **not** a **thread-safe** operation on
14
+ # `Concurrent::Set`. It reads Set `a`, then it creates new `Concurrent::Set`
15
+ # which is union of `a` and `b`, then it writes the union to `a`.
16
+ # The read and write are independent operations they do not form a single atomic
17
+ # operation therefore when two `+=` operations are executed concurrently updates
18
+ # may be lost. Use `#merge` instead.
19
+ #
20
+ # @see http://ruby-doc.org/stdlib-2.4.0/libdoc/set/rdoc/Set.html Ruby standard library `Set`
21
+
22
+ # @!macro internal_implementation_note
23
+ SetImplementation = case
24
+ when Concurrent.on_cruby?
25
+ # The CRuby implementation of Set is written in Ruby itself and is
26
+ # not thread safe for certain methods.
27
+ require 'monitor'
28
+ require 'concurrent/thread_safe/util/data_structures'
29
+
30
+ class CRubySet < ::Set
31
+ end
32
+
33
+ ThreadSafe::Util.make_synchronized_on_cruby CRubySet
34
+ CRubySet
35
+
36
+ when Concurrent.on_jruby?
37
+ require 'jruby/synchronized'
38
+
39
+ class JRubySet < ::Set
40
+ include JRuby::Synchronized
41
+ end
42
+
43
+ JRubySet
44
+
45
+ when Concurrent.on_rbx?
46
+ require 'monitor'
47
+ require 'concurrent/thread_safe/util/data_structures'
48
+
49
+ class RbxSet < ::Set
50
+ end
51
+
52
+ ThreadSafe::Util.make_synchronized_on_rbx RbxSet
53
+ RbxSet
54
+
55
+ when Concurrent.on_truffleruby?
56
+ require 'concurrent/thread_safe/util/data_structures'
57
+
58
+ class TruffleRubySet < ::Set
59
+ end
60
+
61
+ ThreadSafe::Util.make_synchronized_on_truffleruby TruffleRubySet
62
+ TruffleRubySet
63
+
64
+ else
65
+ warn 'Possibly unsupported Ruby implementation'
66
+ ::Set
67
+ end
68
+ private_constant :SetImplementation
69
+
70
+ # @!macro concurrent_set
71
+ class Set < SetImplementation
72
+ end
73
+ end
74
+
@@ -0,0 +1,139 @@
1
+ require 'concurrent/synchronization/abstract_struct'
2
+ require 'concurrent/errors'
3
+ require 'concurrent/synchronization'
4
+
5
+ module Concurrent
6
+
7
+ # An thread-safe, write-once variation of Ruby's standard `Struct`.
8
+ # Each member can have its value set at most once, either at construction
9
+ # or any time thereafter. Attempting to assign a value to a member
10
+ # that has already been set will result in a `Concurrent::ImmutabilityError`.
11
+ #
12
+ # @see http://ruby-doc.org/core/Struct.html Ruby standard library `Struct`
13
+ # @see http://en.wikipedia.org/wiki/Final_(Java) Java `final` keyword
14
+ module SettableStruct
15
+ include Synchronization::AbstractStruct
16
+
17
+ # @!macro struct_values
18
+ def values
19
+ synchronize { ns_values }
20
+ end
21
+ alias_method :to_a, :values
22
+
23
+ # @!macro struct_values_at
24
+ def values_at(*indexes)
25
+ synchronize { ns_values_at(indexes) }
26
+ end
27
+
28
+ # @!macro struct_inspect
29
+ def inspect
30
+ synchronize { ns_inspect }
31
+ end
32
+ alias_method :to_s, :inspect
33
+
34
+ # @!macro struct_merge
35
+ def merge(other, &block)
36
+ synchronize { ns_merge(other, &block) }
37
+ end
38
+
39
+ # @!macro struct_to_h
40
+ def to_h
41
+ synchronize { ns_to_h }
42
+ end
43
+
44
+ # @!macro struct_get
45
+ def [](member)
46
+ synchronize { ns_get(member) }
47
+ end
48
+
49
+ # @!macro struct_equality
50
+ def ==(other)
51
+ synchronize { ns_equality(other) }
52
+ end
53
+
54
+ # @!macro struct_each
55
+ def each(&block)
56
+ return enum_for(:each) unless block_given?
57
+ synchronize { ns_each(&block) }
58
+ end
59
+
60
+ # @!macro struct_each_pair
61
+ def each_pair(&block)
62
+ return enum_for(:each_pair) unless block_given?
63
+ synchronize { ns_each_pair(&block) }
64
+ end
65
+
66
+ # @!macro struct_select
67
+ def select(&block)
68
+ return enum_for(:select) unless block_given?
69
+ synchronize { ns_select(&block) }
70
+ end
71
+
72
+ # @!macro struct_set
73
+ #
74
+ # @raise [Concurrent::ImmutabilityError] if the given member has already been set
75
+ def []=(member, value)
76
+ if member.is_a? Integer
77
+ length = synchronize { @values.length }
78
+ if member >= length
79
+ raise IndexError.new("offset #{member} too large for struct(size:#{length})")
80
+ end
81
+ synchronize do
82
+ unless @values[member].nil?
83
+ raise Concurrent::ImmutabilityError.new('struct member has already been set')
84
+ end
85
+ @values[member] = value
86
+ end
87
+ else
88
+ send("#{member}=", value)
89
+ end
90
+ rescue NoMethodError
91
+ raise NameError.new("no member '#{member}' in struct")
92
+ end
93
+
94
+ private
95
+
96
+ # @!visibility private
97
+ def initialize_copy(original)
98
+ synchronize do
99
+ super(original)
100
+ ns_initialize_copy
101
+ end
102
+ end
103
+
104
+ # @!macro struct_new
105
+ def self.new(*args, &block)
106
+ clazz_name = nil
107
+ if args.length == 0
108
+ raise ArgumentError.new('wrong number of arguments (0 for 1+)')
109
+ elsif args.length > 0 && args.first.is_a?(String)
110
+ clazz_name = args.shift
111
+ end
112
+ FACTORY.define_struct(clazz_name, args, &block)
113
+ end
114
+
115
+ FACTORY = Class.new(Synchronization::LockableObject) do
116
+ def define_struct(name, members, &block)
117
+ synchronize do
118
+ clazz = Synchronization::AbstractStruct.define_struct_class(SettableStruct, Synchronization::LockableObject, name, members, &block)
119
+ members.each_with_index do |member, index|
120
+ clazz.send :remove_method, member if clazz.instance_methods.include? member
121
+ clazz.send(:define_method, member) do
122
+ synchronize { @values[index] }
123
+ end
124
+ clazz.send(:define_method, "#{member}=") do |value|
125
+ synchronize do
126
+ unless @values[index].nil?
127
+ raise Concurrent::ImmutabilityError.new('struct member has already been set')
128
+ end
129
+ @values[index] = value
130
+ end
131
+ end
132
+ end
133
+ clazz
134
+ end
135
+ end
136
+ end.new
137
+ private_constant :FACTORY
138
+ end
139
+ end
@@ -0,0 +1,98 @@
1
+ module Concurrent
2
+ module Synchronization
3
+
4
+ # @!visibility private
5
+ class AbstractLockableObject < Synchronization::Object
6
+
7
+ protected
8
+
9
+ # @!macro synchronization_object_method_synchronize
10
+ #
11
+ # @yield runs the block synchronized against this object,
12
+ # equivalent of java's `synchronize(this) {}`
13
+ # @note can by made public in descendants if required by `public :synchronize`
14
+ def synchronize
15
+ raise NotImplementedError
16
+ end
17
+
18
+ # @!macro synchronization_object_method_ns_wait_until
19
+ #
20
+ # Wait until condition is met or timeout passes,
21
+ # protects against spurious wake-ups.
22
+ # @param [Numeric, nil] timeout in seconds, `nil` means no timeout
23
+ # @yield condition to be met
24
+ # @yieldreturn [true, false]
25
+ # @return [true, false] if condition met
26
+ # @note only to be used inside synchronized block
27
+ # @note to provide direct access to this method in a descendant add method
28
+ # ```
29
+ # def wait_until(timeout = nil, &condition)
30
+ # synchronize { ns_wait_until(timeout, &condition) }
31
+ # end
32
+ # ```
33
+ def ns_wait_until(timeout = nil, &condition)
34
+ if timeout
35
+ wait_until = Concurrent.monotonic_time + timeout
36
+ loop do
37
+ now = Concurrent.monotonic_time
38
+ condition_result = condition.call
39
+ return condition_result if now >= wait_until || condition_result
40
+ ns_wait wait_until - now
41
+ end
42
+ else
43
+ ns_wait timeout until condition.call
44
+ true
45
+ end
46
+ end
47
+
48
+ # @!macro synchronization_object_method_ns_wait
49
+ #
50
+ # Wait until another thread calls #signal or #broadcast,
51
+ # spurious wake-ups can happen.
52
+ #
53
+ # @param [Numeric, nil] timeout in seconds, `nil` means no timeout
54
+ # @return [self]
55
+ # @note only to be used inside synchronized block
56
+ # @note to provide direct access to this method in a descendant add method
57
+ # ```
58
+ # def wait(timeout = nil)
59
+ # synchronize { ns_wait(timeout) }
60
+ # end
61
+ # ```
62
+ def ns_wait(timeout = nil)
63
+ raise NotImplementedError
64
+ end
65
+
66
+ # @!macro synchronization_object_method_ns_signal
67
+ #
68
+ # Signal one waiting thread.
69
+ # @return [self]
70
+ # @note only to be used inside synchronized block
71
+ # @note to provide direct access to this method in a descendant add method
72
+ # ```
73
+ # def signal
74
+ # synchronize { ns_signal }
75
+ # end
76
+ # ```
77
+ def ns_signal
78
+ raise NotImplementedError
79
+ end
80
+
81
+ # @!macro synchronization_object_method_ns_broadcast
82
+ #
83
+ # Broadcast to all waiting threads.
84
+ # @return [self]
85
+ # @note only to be used inside synchronized block
86
+ # @note to provide direct access to this method in a descendant add method
87
+ # ```
88
+ # def broadcast
89
+ # synchronize { ns_broadcast }
90
+ # end
91
+ # ```
92
+ def ns_broadcast
93
+ raise NotImplementedError
94
+ end
95
+
96
+ end
97
+ end
98
+ end