concurrent-ruby 0.8.0 → 0.9.0.pre2

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 (144) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +97 -2
  3. data/README.md +103 -54
  4. data/lib/concurrent.rb +34 -14
  5. data/lib/concurrent/async.rb +164 -50
  6. data/lib/concurrent/atom.rb +171 -0
  7. data/lib/concurrent/atomic/atomic_boolean.rb +57 -107
  8. data/lib/concurrent/atomic/atomic_fixnum.rb +73 -101
  9. data/lib/concurrent/atomic/atomic_reference.rb +49 -0
  10. data/lib/concurrent/atomic/condition.rb +23 -12
  11. data/lib/concurrent/atomic/count_down_latch.rb +23 -21
  12. data/lib/concurrent/atomic/cyclic_barrier.rb +47 -47
  13. data/lib/concurrent/atomic/event.rb +33 -42
  14. data/lib/concurrent/atomic/read_write_lock.rb +252 -0
  15. data/lib/concurrent/atomic/semaphore.rb +64 -89
  16. data/lib/concurrent/atomic/thread_local_var.rb +130 -58
  17. data/lib/concurrent/atomic/thread_local_var/weak_key_map.rb +236 -0
  18. data/lib/concurrent/atomic_reference/direct_update.rb +3 -0
  19. data/lib/concurrent/atomic_reference/jruby.rb +6 -3
  20. data/lib/concurrent/atomic_reference/mutex_atomic.rb +10 -32
  21. data/lib/concurrent/atomic_reference/numeric_cas_wrapper.rb +3 -0
  22. data/lib/concurrent/atomic_reference/rbx.rb +4 -1
  23. data/lib/concurrent/atomic_reference/ruby.rb +6 -3
  24. data/lib/concurrent/atomics.rb +74 -4
  25. data/lib/concurrent/collection/copy_on_notify_observer_set.rb +115 -0
  26. data/lib/concurrent/collection/copy_on_write_observer_set.rb +119 -0
  27. data/lib/concurrent/collection/priority_queue.rb +300 -245
  28. data/lib/concurrent/concern/deprecation.rb +27 -0
  29. data/lib/concurrent/concern/dereferenceable.rb +88 -0
  30. data/lib/concurrent/concern/logging.rb +25 -0
  31. data/lib/concurrent/concern/obligation.rb +228 -0
  32. data/lib/concurrent/concern/observable.rb +85 -0
  33. data/lib/concurrent/configuration.rb +226 -112
  34. data/lib/concurrent/dataflow.rb +2 -3
  35. data/lib/concurrent/delay.rb +141 -50
  36. data/lib/concurrent/edge.rb +30 -0
  37. data/lib/concurrent/errors.rb +10 -0
  38. data/lib/concurrent/exchanger.rb +25 -1
  39. data/lib/concurrent/executor/cached_thread_pool.rb +46 -33
  40. data/lib/concurrent/executor/executor.rb +46 -299
  41. data/lib/concurrent/executor/executor_service.rb +521 -0
  42. data/lib/concurrent/executor/fixed_thread_pool.rb +206 -26
  43. data/lib/concurrent/executor/immediate_executor.rb +9 -9
  44. data/lib/concurrent/executor/indirect_immediate_executor.rb +4 -3
  45. data/lib/concurrent/executor/java_cached_thread_pool.rb +18 -16
  46. data/lib/concurrent/executor/java_fixed_thread_pool.rb +11 -18
  47. data/lib/concurrent/executor/java_single_thread_executor.rb +17 -16
  48. data/lib/concurrent/executor/java_thread_pool_executor.rb +55 -102
  49. data/lib/concurrent/executor/ruby_cached_thread_pool.rb +9 -18
  50. data/lib/concurrent/executor/ruby_fixed_thread_pool.rb +10 -21
  51. data/lib/concurrent/executor/ruby_single_thread_executor.rb +14 -16
  52. data/lib/concurrent/executor/ruby_thread_pool_executor.rb +250 -166
  53. data/lib/concurrent/executor/safe_task_executor.rb +5 -4
  54. data/lib/concurrent/executor/serialized_execution.rb +22 -18
  55. data/lib/concurrent/executor/{per_thread_executor.rb → simple_executor_service.rb} +29 -20
  56. data/lib/concurrent/executor/single_thread_executor.rb +32 -21
  57. data/lib/concurrent/executor/thread_pool_executor.rb +72 -60
  58. data/lib/concurrent/executor/timer_set.rb +96 -84
  59. data/lib/concurrent/executors.rb +1 -1
  60. data/lib/concurrent/future.rb +70 -38
  61. data/lib/concurrent/immutable_struct.rb +89 -0
  62. data/lib/concurrent/ivar.rb +152 -60
  63. data/lib/concurrent/lazy_register.rb +40 -20
  64. data/lib/concurrent/maybe.rb +226 -0
  65. data/lib/concurrent/mutable_struct.rb +227 -0
  66. data/lib/concurrent/mvar.rb +44 -43
  67. data/lib/concurrent/promise.rb +208 -134
  68. data/lib/concurrent/scheduled_task.rb +339 -43
  69. data/lib/concurrent/settable_struct.rb +127 -0
  70. data/lib/concurrent/synchronization.rb +17 -0
  71. data/lib/concurrent/synchronization/abstract_object.rb +163 -0
  72. data/lib/concurrent/synchronization/abstract_struct.rb +158 -0
  73. data/lib/concurrent/synchronization/condition.rb +53 -0
  74. data/lib/concurrent/synchronization/java_object.rb +35 -0
  75. data/lib/concurrent/synchronization/lock.rb +32 -0
  76. data/lib/concurrent/synchronization/monitor_object.rb +24 -0
  77. data/lib/concurrent/synchronization/mutex_object.rb +43 -0
  78. data/lib/concurrent/synchronization/object.rb +78 -0
  79. data/lib/concurrent/synchronization/rbx_object.rb +75 -0
  80. data/lib/concurrent/timer_task.rb +87 -100
  81. data/lib/concurrent/tvar.rb +42 -38
  82. data/lib/concurrent/utilities.rb +3 -1
  83. data/lib/concurrent/utility/at_exit.rb +97 -0
  84. data/lib/concurrent/utility/engine.rb +40 -0
  85. data/lib/concurrent/utility/monotonic_time.rb +59 -0
  86. data/lib/concurrent/utility/native_extension_loader.rb +56 -0
  87. data/lib/concurrent/utility/processor_counter.rb +156 -0
  88. data/lib/concurrent/utility/timeout.rb +18 -14
  89. data/lib/concurrent/utility/timer.rb +11 -6
  90. data/lib/concurrent/version.rb +2 -1
  91. data/lib/concurrent_ruby.rb +1 -0
  92. metadata +47 -83
  93. data/lib/concurrent/actor.rb +0 -103
  94. data/lib/concurrent/actor/behaviour.rb +0 -70
  95. data/lib/concurrent/actor/behaviour/abstract.rb +0 -48
  96. data/lib/concurrent/actor/behaviour/awaits.rb +0 -21
  97. data/lib/concurrent/actor/behaviour/buffer.rb +0 -54
  98. data/lib/concurrent/actor/behaviour/errors_on_unknown_message.rb +0 -12
  99. data/lib/concurrent/actor/behaviour/executes_context.rb +0 -18
  100. data/lib/concurrent/actor/behaviour/linking.rb +0 -45
  101. data/lib/concurrent/actor/behaviour/pausing.rb +0 -77
  102. data/lib/concurrent/actor/behaviour/removes_child.rb +0 -16
  103. data/lib/concurrent/actor/behaviour/sets_results.rb +0 -36
  104. data/lib/concurrent/actor/behaviour/supervised.rb +0 -59
  105. data/lib/concurrent/actor/behaviour/supervising.rb +0 -34
  106. data/lib/concurrent/actor/behaviour/terminates_children.rb +0 -13
  107. data/lib/concurrent/actor/behaviour/termination.rb +0 -54
  108. data/lib/concurrent/actor/context.rb +0 -154
  109. data/lib/concurrent/actor/core.rb +0 -217
  110. data/lib/concurrent/actor/default_dead_letter_handler.rb +0 -9
  111. data/lib/concurrent/actor/envelope.rb +0 -41
  112. data/lib/concurrent/actor/errors.rb +0 -27
  113. data/lib/concurrent/actor/internal_delegations.rb +0 -49
  114. data/lib/concurrent/actor/public_delegations.rb +0 -40
  115. data/lib/concurrent/actor/reference.rb +0 -81
  116. data/lib/concurrent/actor/root.rb +0 -37
  117. data/lib/concurrent/actor/type_check.rb +0 -48
  118. data/lib/concurrent/actor/utils.rb +0 -10
  119. data/lib/concurrent/actor/utils/ad_hoc.rb +0 -21
  120. data/lib/concurrent/actor/utils/balancer.rb +0 -42
  121. data/lib/concurrent/actor/utils/broadcast.rb +0 -52
  122. data/lib/concurrent/actor/utils/pool.rb +0 -59
  123. data/lib/concurrent/actress.rb +0 -3
  124. data/lib/concurrent/agent.rb +0 -209
  125. data/lib/concurrent/atomic.rb +0 -92
  126. data/lib/concurrent/atomic/copy_on_notify_observer_set.rb +0 -118
  127. data/lib/concurrent/atomic/copy_on_write_observer_set.rb +0 -117
  128. data/lib/concurrent/atomic/synchronization.rb +0 -51
  129. data/lib/concurrent/channel/buffered_channel.rb +0 -85
  130. data/lib/concurrent/channel/channel.rb +0 -41
  131. data/lib/concurrent/channel/unbuffered_channel.rb +0 -35
  132. data/lib/concurrent/channel/waitable_list.rb +0 -40
  133. data/lib/concurrent/channels.rb +0 -5
  134. data/lib/concurrent/collection/blocking_ring_buffer.rb +0 -71
  135. data/lib/concurrent/collection/ring_buffer.rb +0 -59
  136. data/lib/concurrent/collections.rb +0 -3
  137. data/lib/concurrent/dereferenceable.rb +0 -108
  138. data/lib/concurrent/executor/ruby_thread_pool_worker.rb +0 -73
  139. data/lib/concurrent/logging.rb +0 -20
  140. data/lib/concurrent/obligation.rb +0 -171
  141. data/lib/concurrent/observable.rb +0 -73
  142. data/lib/concurrent/options_parser.rb +0 -52
  143. data/lib/concurrent/utility/processor_count.rb +0 -152
  144. data/lib/extension_helper.rb +0 -37
@@ -1,79 +1,375 @@
1
+ require 'concurrent/errors'
1
2
  require 'concurrent/ivar'
2
- require 'concurrent/utility/timer'
3
- require 'concurrent/executor/safe_task_executor'
3
+ require 'concurrent/configuration'
4
+ require 'concurrent/collection/copy_on_notify_observer_set'
5
+ require 'concurrent/executor/executor'
6
+ require 'concurrent/executor/timer_set'
7
+ require 'concurrent/utility/monotonic_time'
4
8
 
5
9
  module Concurrent
6
10
 
7
- # {include:file:doc/scheduled_task.md}
11
+ # `ScheduledTask` is a close relative of `Concurrent::Future` but with one
12
+ # important difference: A `Future` is set to execute as soon as possible
13
+ # whereas a `ScheduledTask` is set to execute after a specified delay. This
14
+ # implementation is loosely based on Java's
15
+ # [ScheduledExecutorService](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html).
16
+ # It is a more feature-rich variant of {Concurrent.timer}.
17
+ #
18
+ # The *intended* schedule time of task execution is set on object construction
19
+ # with the `delay` argument. The delay is a numeric (floating point or integer)
20
+ # representing a number of seconds in the future. Any other value or a numeric
21
+ # equal to or less than zero will result in an exception. The *actual* schedule
22
+ # time of task execution is set when the `execute` method is called.
23
+ #
24
+ # The constructor can also be given zero or more processing options. Currently
25
+ # the only supported options are those recognized by the
26
+ # [Dereferenceable](Dereferenceable) module.
27
+ #
28
+ # The final constructor argument is a block representing the task to be performed.
29
+ # If no block is given an `ArgumentError` will be raised.
30
+ #
31
+ # **States**
32
+ #
33
+ # `ScheduledTask` mixes in the [Obligation](Obligation) module thus giving it
34
+ # "future" behavior. This includes the expected lifecycle states. `ScheduledTask`
35
+ # has one additional state, however. While the task (block) is being executed the
36
+ # state of the object will be `:processing`. This additional state is necessary
37
+ # because it has implications for task cancellation.
38
+ #
39
+ # **Cancellation**
40
+ #
41
+ # A `:pending` task can be cancelled using the `#cancel` method. A task in any
42
+ # other state, including `:processing`, cannot be cancelled. The `#cancel`
43
+ # method returns a boolean indicating the success of the cancellation attempt.
44
+ # A cancelled `ScheduledTask` cannot be restarted. It is immutable.
45
+ #
46
+ # **Obligation and Observation**
47
+ #
48
+ # The result of a `ScheduledTask` can be obtained either synchronously or
49
+ # asynchronously. `ScheduledTask` mixes in both the [Obligation](Obligation)
50
+ # module and the
51
+ # [Observable](http://ruby-doc.org/stdlib-2.0/libdoc/observer/rdoc/Observable.html)
52
+ # module from the Ruby standard library. With one exception `ScheduledTask`
53
+ # behaves identically to [Future](Observable) with regard to these modules.
54
+ #
55
+ # @!macro copy_options
56
+ #
57
+ # @example Basic usage
58
+ #
59
+ # require 'concurrent'
60
+ # require 'thread' # for Queue
61
+ # require 'open-uri' # for open(uri)
62
+ #
63
+ # class Ticker
64
+ # def get_year_end_closing(symbol, year)
65
+ # uri = "http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=11&b=01&c=#{year}&d=11&e=31&f=#{year}&g=m"
66
+ # data = open(uri) {|f| f.collect{|line| line.strip } }
67
+ # data[1].split(',')[4].to_f
68
+ # end
69
+ # end
70
+ #
71
+ # # Future
72
+ # price = Concurrent::Future.execute{ Ticker.new.get_year_end_closing('TWTR', 2013) }
73
+ # price.state #=> :pending
74
+ # sleep(1) # do other stuff
75
+ # price.value #=> 63.65
76
+ # price.state #=> :fulfilled
77
+ #
78
+ # # ScheduledTask
79
+ # task = Concurrent::ScheduledTask.execute(2){ Ticker.new.get_year_end_closing('INTC', 2013) }
80
+ # task.state #=> :pending
81
+ # sleep(3) # do other stuff
82
+ # task.value #=> 25.96
83
+ #
84
+ # @example Successful task execution
85
+ #
86
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
87
+ # task.state #=> :unscheduled
88
+ # task.execute
89
+ # task.state #=> pending
90
+ #
91
+ # # wait for it...
92
+ # sleep(3)
93
+ #
94
+ # task.unscheduled? #=> false
95
+ # task.pending? #=> false
96
+ # task.fulfilled? #=> true
97
+ # task.rejected? #=> false
98
+ # task.value #=> 'What does the fox say?'
99
+ #
100
+ # @example One line creation and execution
101
+ #
102
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }.execute
103
+ # task.state #=> pending
104
+ #
105
+ # task = Concurrent::ScheduledTask.execute(2){ 'What do you get when you multiply 6 by 9?' }
106
+ # task.state #=> pending
107
+ #
108
+ # @example Failed task execution
109
+ #
110
+ # task = Concurrent::ScheduledTask.execute(2){ raise StandardError.new('Call me maybe?') }
111
+ # task.pending? #=> true
112
+ #
113
+ # # wait for it...
114
+ # sleep(3)
115
+ #
116
+ # task.unscheduled? #=> false
117
+ # task.pending? #=> false
118
+ # task.fulfilled? #=> false
119
+ # task.rejected? #=> true
120
+ # task.value #=> nil
121
+ # task.reason #=> #<StandardError: Call me maybe?>
122
+ #
123
+ # @example Task execution with observation
124
+ #
125
+ # observer = Class.new{
126
+ # def update(time, value, reason)
127
+ # puts "The task completed at #{time} with value '#{value}'"
128
+ # end
129
+ # }.new
130
+ #
131
+ # task = Concurrent::ScheduledTask.new(2){ 'What does the fox say?' }
132
+ # task.add_observer(observer)
133
+ # task.execute
134
+ # task.pending? #=> true
135
+ #
136
+ # # wait for it...
137
+ # sleep(3)
138
+ #
139
+ # #>> The task completed at 2013-11-07 12:26:09 -0500 with value 'What does the fox say?'
140
+ #
141
+ # @!macro monotonic_clock_warning
142
+ #
143
+ # @see Concurrent.timer
8
144
  class ScheduledTask < IVar
145
+ include Comparable
9
146
 
10
- attr_reader :schedule_time
147
+ # The executor on which to execute the task.
148
+ # @!visibility private
149
+ attr_reader :executor
11
150
 
12
- def initialize(intended_time, opts = {}, &block)
151
+ # Schedule a task for execution at a specified future time.
152
+ #
153
+ # @param [Float] delay the number of seconds to wait for before executing the task
154
+ #
155
+ # @yield the task to be performed
156
+ #
157
+ # @!macro executor_and_deref_options
158
+ #
159
+ # @option opts [object, Array] :args zero or more arguments to be passed the task
160
+ # block on execution
161
+ #
162
+ # @raise [ArgumentError] When no block is given
163
+ # @raise [ArgumentError] When given a time that is in the past
164
+ #
165
+ # @!macro [attach] deprecated_scheduling_by_clock_time
166
+ #
167
+ # @note Scheduling is now based on a monotonic clock. This makes the timer much
168
+ # more accurate, but only when scheduling based on a delay interval.
169
+ # Scheduling a task based on a clock time is deprecated. It will still work
170
+ # but will not be supported in the 1.0 release.
171
+ def initialize(delay, opts = {}, &task)
13
172
  raise ArgumentError.new('no block given') unless block_given?
14
- TimerSet.calculate_schedule_time(intended_time) # raises exceptons
173
+ super(IVar::NO_VALUE, opts, &nil)
174
+ synchronize do
175
+ @delay = calculate_delay!(delay) # may raise exception
176
+ ns_set_state(:unscheduled)
177
+ @parent = opts.fetch(:timer_set, Concurrent.global_timer_set)
178
+ @args = get_arguments_from(opts)
179
+ @task = task
180
+ @time = nil
181
+ @executor = Executor.executor_from_options(opts) || Concurrent.global_io_executor
182
+ self.observers = Collection::CopyOnNotifyObserverSet.new
183
+ end
184
+ end
15
185
 
16
- super(NO_VALUE, opts)
186
+ # The `delay` value given at instanciation.
187
+ #
188
+ # @return [Float] the initial delay.
189
+ def initial_delay
190
+ synchronize { @delay }
191
+ end
17
192
 
18
- self.observers = CopyOnNotifyObserverSet.new
19
- @intended_time = intended_time
20
- @state = :unscheduled
21
- @task = block
22
- @executor = OptionsParser::get_executor_from(opts) || Concurrent.configuration.global_operation_pool
193
+ # The `delay` value given at instanciation.
194
+ #
195
+ # @return [Float] the initial delay.
196
+ #
197
+ # @deprecated use {#initial_delay} instead
198
+ def delay
199
+ warn '[DEPRECATED] use #initial_delay instead'
200
+ initial_delay
23
201
  end
24
202
 
25
- # @since 0.5.0
26
- def execute
27
- if compare_and_set_state(:pending, :unscheduled)
28
- @schedule_time = TimerSet.calculate_schedule_time(@intended_time)
29
- Concurrent::timer(@schedule_time.to_f - Time.now.to_f) { @executor.post(&method(:process_task)) }
30
- self
31
- end
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 }
32
208
  end
33
209
 
34
- # @since 0.5.0
35
- def self.execute(intended_time, opts = {}, &block)
36
- return ScheduledTask.new(intended_time, opts, &block).execute
210
+ # Comparator which orders by schedule time.
211
+ #
212
+ # @!visibility private
213
+ def <=>(other)
214
+ schedule_time <=> other.schedule_time
37
215
  end
38
216
 
217
+ # Has the task been cancelled?
218
+ #
219
+ # @return [Boolean] true if the task is in the given state else false
39
220
  def cancelled?
40
- state == :cancelled
221
+ synchronize { ns_check_state?(:cancelled) }
41
222
  end
42
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
+ # In the task execution in progress?
232
+ #
233
+ # @return [Boolean] true if the task is in the given state else false
234
+ #
235
+ # @deprecated Use {#processing?} instead.
43
236
  def in_progress?
44
- state == :in_progress
237
+ warn '[DEPRECATED] use #processing? instead'
238
+ processing?
45
239
  end
46
240
 
241
+ # Cancel this task and prevent it from executing. A task can only be
242
+ # cancelled if it is pending or unscheduled.
243
+ #
244
+ # @return [Boolean] true if successfully cancelled else false
47
245
  def cancel
48
- if_state(:unscheduled, :pending) do
49
- @state = :cancelled
50
- event.set
51
- true
246
+ if compare_and_set_state(:cancelled, :pending, :unscheduled)
247
+ complete(false, nil, CancelledOperationError.new)
248
+ # To avoid deadlocks this call must occur outside of #synchronize
249
+ # Changing the state above should prevent redundant calls
250
+ @parent.send(:remove_task, self)
251
+ else
252
+ false
52
253
  end
53
254
  end
54
- alias_method :stop, :cancel
55
255
 
56
- def add_observer(*args, &block)
57
- if_state(:unscheduled, :pending, :in_progress) do
58
- observers.add_observer(*args, &block)
59
- end
256
+ # Cancel this task and prevent it from executing. A task can only be
257
+ # cancelled if it is `:pending` or `:unscheduled`.
258
+ #
259
+ # @return [Boolean] true if successfully cancelled else false
260
+ #
261
+ # @deprecated Use {#cancel} instead.
262
+ def stop
263
+ warn '[DEPRECATED] use #cancel instead'
264
+ cancel
265
+ end
266
+
267
+ # Reschedule the task using the original delay and the current time.
268
+ # A task can only be reset while it is `:pending`.
269
+ #
270
+ # @return [Boolean] true if successfully rescheduled else false
271
+ def reset
272
+ synchronize{ ns_reschedule(@delay) }
273
+ end
274
+
275
+ # Reschedule the task using the given delay and the current time.
276
+ # A task can only be reset while it is `:pending`.
277
+ #
278
+ # @param [Float] delay the number of seconds to wait for before executing the task
279
+ #
280
+ # @return [Boolean] true if successfully rescheduled else false
281
+ #
282
+ # @raise [ArgumentError] When given a time that is in the past
283
+ def reschedule(delay)
284
+ synchronize{ ns_reschedule(calculate_delay!(delay)) }
60
285
  end
61
286
 
62
- protected :set, :fail, :complete
287
+ # Execute an `:unscheduled` `ScheduledTask`. Immediately sets the state to `:pending`
288
+ # and starts counting down toward execution. Does nothing if the `ScheduledTask` is
289
+ # in any state other than `:unscheduled`.
290
+ #
291
+ # @return [ScheduledTask] a reference to `self`
292
+ def execute
293
+ if compare_and_set_state(:pending, :unscheduled)
294
+ synchronize{ ns_schedule(@delay) }
295
+ end
296
+ self
297
+ end
63
298
 
64
- private
299
+ # Create a new `ScheduledTask` object with the given block, execute it, and return the
300
+ # `:pending` object.
301
+ #
302
+ # @param [Float] delay the number of seconds to wait for before executing the task
303
+ #
304
+ # @!macro executor_and_deref_options
305
+ #
306
+ # @return [ScheduledTask] the newly created `ScheduledTask` in the `:pending` state
307
+ #
308
+ # @raise [ArgumentError] if no block is given
309
+ #
310
+ # @!macro deprecated_scheduling_by_clock_time
311
+ def self.execute(delay, opts = {}, &task)
312
+ new(delay, opts, &task).execute
313
+ end
65
314
 
315
+ # Execute the task.
316
+ #
317
+ # @!visibility private
66
318
  def process_task
67
- if compare_and_set_state(:in_progress, :pending)
68
- success, val, reason = SafeTaskExecutor.new(@task).execute
319
+ safe_execute(@task, @args)
320
+ end
321
+
322
+ protected :set, :try_set, :fail, :complete
323
+
324
+ protected
69
325
 
70
- mutex.synchronize do
71
- set_state(success, val, reason)
72
- event.set
73
- end
326
+ # Schedule the task using the given delay and the current time.
327
+ #
328
+ # @param [Float] delay the number of seconds to wait for before executing the task
329
+ #
330
+ # @return [Boolean] true if successfully rescheduled else false
331
+ #
332
+ # @!visibility private
333
+ def ns_schedule(delay)
334
+ @delay = delay
335
+ @time = Concurrent.monotonic_time + @delay
336
+ @parent.send(:post_task, self)
337
+ end
338
+
339
+ # Reschedule the task using the given delay and the current time.
340
+ # A task can only be reset while it is `:pending`.
341
+ #
342
+ # @param [Float] delay the number of seconds to wait for before executing the task
343
+ #
344
+ # @return [Boolean] true if successfully rescheduled else false
345
+ #
346
+ # @!visibility private
347
+ def ns_reschedule(delay)
348
+ return false unless ns_check_state?(:pending)
349
+ @parent.send(:remove_task, self) && ns_schedule(delay)
350
+ end
74
351
 
75
- time = Time.now
76
- observers.notify_and_delete_observers { [time, self.value, reason] }
352
+ # Calculate the actual delay in seconds based on the given delay.
353
+ #
354
+ # @param [Float] delay the number of seconds to wait for before executing the task
355
+ #
356
+ # @return [Float] the number of seconds to delay
357
+ #
358
+ # @raise [ArgumentError] if the intended execution time is not in the future
359
+ # @raise [ArgumentError] if no block is given
360
+ #
361
+ # @!macro deprecated_scheduling_by_clock_time
362
+ #
363
+ # @!visibility private
364
+ def calculate_delay!(delay)
365
+ if delay.is_a?(Time)
366
+ warn '[DEPRECATED] Use an interval not a clock time; schedule is now based on a monotonic clock'
367
+ now = Time.now
368
+ raise ArgumentError.new('schedule time must be in the future') if delay <= now
369
+ delay.to_f - now.to_f
370
+ else
371
+ raise ArgumentError.new('seconds must be greater than zero') if delay.to_f < 0.0
372
+ delay.to_f
77
373
  end
78
374
  end
79
375
  end
@@ -0,0 +1,127 @@
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-2.2.0/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
+ if member >= @values.length
78
+ raise IndexError.new("offset #{member} too large for struct(size:#{@values.length})")
79
+ end
80
+ synchronize do
81
+ unless @values[member].nil?
82
+ raise Concurrent::ImmutabilityError.new('struct member has already been set')
83
+ end
84
+ @values[member] = value
85
+ end
86
+ else
87
+ send("#{member}=", value)
88
+ end
89
+ rescue NoMethodError
90
+ raise NameError.new("no member '#{member}' in struct")
91
+ end
92
+
93
+ # @!macro struct_new
94
+ def self.new(*args, &block)
95
+ clazz_name = nil
96
+ if args.length == 0
97
+ raise ArgumentError.new('wrong number of arguments (0 for 1+)')
98
+ elsif args.length > 0 && args.first.is_a?(String)
99
+ clazz_name = args.shift
100
+ end
101
+ FACTORY.define_struct(clazz_name, args, &block)
102
+ end
103
+
104
+ FACTORY = Class.new(Synchronization::Object) do
105
+ def define_struct(name, members, &block)
106
+ synchronize do
107
+ clazz = Synchronization::AbstractStruct.define_struct_class(SettableStruct, Synchronization::Object, name, members, &block)
108
+ members.each_with_index do |member, index|
109
+ clazz.send(:define_method, member) do
110
+ synchronize { @values[index] }
111
+ end
112
+ clazz.send(:define_method, "#{member}=") do |value|
113
+ synchronize do
114
+ unless @values[index].nil?
115
+ raise Concurrent::ImmutabilityError.new('struct member has already been set')
116
+ end
117
+ @values[index] = value
118
+ end
119
+ end
120
+ end
121
+ clazz
122
+ end
123
+ end
124
+ end.new
125
+ private_constant :FACTORY
126
+ end
127
+ end