• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jdantonio / concurrent-ruby / #711

24 Apr 2014 12:31AM UTC coverage: 77.282% (-20.5%) from 97.805%
#711

push

jdantonio
Attempting to fix a brittle test of Concurrent::timer.

1888 of 2443 relevant lines covered (77.28%)

544.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

76.99
/lib/concurrent/executor/ruby_thread_pool_executor.rb
1
require 'thread'
1✔
2

3
require_relative 'executor'
1✔
4
require 'concurrent/atomic/event'
1✔
5
require 'concurrent/executor/ruby_thread_pool_worker'
1✔
6

7
module Concurrent
1✔
8

9
  # @!macro thread_pool_executor
10
  class RubyThreadPoolExecutor
1✔
11
    include Executor
1✔
12

13
    # Default maximum number of threads that will be created in the pool.
14
    DEFAULT_MAX_POOL_SIZE = 2**15 # 32768
1✔
15

16
    # Default minimum number of threads that will be retained in the pool.
17
    DEFAULT_MIN_POOL_SIZE = 0
1✔
18

19
    # Default maximum number of tasks that may be added to the task queue.
20
    DEFAULT_MAX_QUEUE_SIZE = 0
1✔
21

22
    # Default maximum number of seconds a thread in the pool may remain idle
23
    # before being reclaimed.
24
    DEFAULT_THREAD_IDLETIMEOUT = 60
1✔
25

26
    # The set of possible overflow policies that may be set at thread pool creation.
27
    OVERFLOW_POLICIES = [:abort, :discard, :caller_runs]
1✔
28

29
    # The maximum number of threads that may be created in the pool.
30
    attr_reader :max_length
1✔
31

32
    # The minimum number of threads that may be retained in the pool.
33
    attr_reader :min_length
1✔
34

35
    # The largest number of threads that have been created in the pool since construction.
36
    attr_reader :largest_length
1✔
37

38
    # The number of tasks that have been scheduled for execution on the pool since construction.
39
    attr_reader :scheduled_task_count
1✔
40

41
    # The number of tasks that have been completed by the pool since construction.
42
    attr_reader :completed_task_count
1✔
43

44
    # The number of seconds that a thread may be idle before being reclaimed.
45
    attr_reader :idletime
1✔
46

47
    # The maximum number of tasks that may be waiting in the work queue at any one time.
48
    # When the queue size reaches `max_queue` subsequent tasks will be rejected in
49
    # accordance with the configured `overflow_policy`.
50
    attr_reader :max_queue
1✔
51

52
    # The policy defining how rejected tasks (tasks received once the queue size reaches
53
    # the configured `max_queue`) are handled. Must be one of the values specified in
54
    # `OVERFLOW_POLICIES`.
55
    attr_reader :overflow_policy
1✔
56

57
    # Create a new thread pool.
58
    #
59
    # @param [Hash] opts the options which configure the thread pool
60
    #
61
    # @option opts [Integer] :max_threads (DEFAULT_MAX_POOL_SIZE) the maximum
62
    #   number of threads to be created
63
    # @option opts [Integer] :min_threads (DEFAULT_MIN_POOL_SIZE) the minimum
64
    #   number of threads to be retained
65
    # @option opts [Integer] :idletime (DEFAULT_THREAD_IDLETIMEOUT) the maximum
66
    #   number of seconds a thread may be idle before being reclaimed
67
    # @option opts [Integer] :max_queue (DEFAULT_MAX_QUEUE_SIZE) the maximum
68
    #   number of tasks allowed in the work queue at any one time; a value of
69
    #   zero means the queue may grow without bounnd
70
    # @option opts [Symbol] :overflow_policy (:abort) the policy for handling new
71
    #   tasks that are received when the queue size has reached `max_queue`
72
    #
73
    # @raise [ArgumentError] if `:max_threads` is less than one
74
    # @raise [ArgumentError] if `:min_threads` is less than zero
75
    # @raise [ArgumentError] if `:overflow_policy` is not one of the values specified
76
    #   in `OVERFLOW_POLICIES`
77
    #
78
    # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
79
    def initialize(opts = {})
1✔
80
      @min_length = opts.fetch(:min_threads, DEFAULT_MIN_POOL_SIZE).to_i
115✔
81
      @max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i
115✔
82
      @idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i
115✔
83
      @max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i
115✔
84
      @overflow_policy = opts.fetch(:overflow_policy, :abort)
115✔
85

86
      raise ArgumentError.new('max_threads must be greater than zero') if @max_length <= 0
115✔
87
      raise ArgumentError.new('min_threads cannot be less than zero') if @min_length < 0
115✔
88
      raise ArgumentError.new("#{overflow_policy} is not a valid overflow policy") unless OVERFLOW_POLICIES.include?(@overflow_policy)
115✔
89

90
      init_executor
115✔
91

92
      @pool = []
115✔
93
      @queue = Queue.new
115✔
94
      @scheduled_task_count = 0
115✔
95
      @completed_task_count = 0
115✔
96
      @largest_length = 0
115✔
97

98
      @gc_interval = opts.fetch(:gc_interval, 1).to_i # undocumented
115✔
99
      @last_gc_time = Time.now.to_f - [1.0, (@gc_interval * 2.0)].max
115✔
100
    end
101

102
    # The number of threads currently in the pool.
103
    #
104
    # @return [Integer] the length
105
    def length
1✔
106
      mutex.synchronize{ running? ? @pool.length : 0 }
×
107
    end
108
    alias_method :current_length, :length
1✔
109

110
    # The number of tasks in the queue awaiting execution.
111
    #
112
    # @return [Integer] the queue_length
113
    def queue_length
1✔
114
      mutex.synchronize{ running? ? @queue.length : 0 }
×
115
    end
116

117
    # Number of tasks that may be enqueued before reaching `max_queue` and rejecting
118
    # new tasks. A value of -1 indicates that the queue may grow without bound.
119
    #
120
    # @return [Integer] the remaining_capacity
121
    def remaining_capacity
1✔
122
      mutex.synchronize { @max_queue == 0 ? -1 : @max_queue - @queue.length }
×
123
    end
124

125
    # Returns an array with the status of each thread in the pool
126
    #
127
    # This method is deprecated and will be removed soon.
128
    def status
1✔
129
      warn '[DEPRECATED] `status` is deprecated and will be removed soon.'
×
130
      mutex.synchronize { @pool.collect { |worker| worker.status } }
×
131
    end
132

133
    # Run on task completion.
134
    #
135
    # @!visibility private
136
    def on_end_task
1✔
137
      mutex.synchronize do
1,324✔
138
        @completed_task_count += 1 #if success
1,324✔
139
        break unless running?
1,324✔
140
      end
141
    end
142

143
    # Run when a thread worker exits.
144
    #
145
    # @!visibility private
146
    def on_worker_exit(worker)
1✔
147
      mutex.synchronize do
×
148
        @pool.delete(worker)
×
149
        if @pool.empty? && ! running?
×
150
          stop_event.set
×
151
          stopped_event.set
×
152
        end
153
      end
154
    end
155

156
    protected
1✔
157

158
    # @!visibility private
159
    def execute(*args, &task)
1✔
160
      prune_pool
1,343✔
161
      if ensure_capacity?
1,343✔
162
        @scheduled_task_count += 1
1,343✔
163
        @queue << [args, task]
1,343✔
164
      else
165
        handle_overflow(*args, &task) if @max_queue != 0 && @queue.length >= @max_queue
×
166
      end
167
    end
168

169
    # @!visibility private
170
    def shutdown_execution
1✔
171
      @queue.clear
2✔
172
      if @pool.empty?
2✔
173
        stopped_event.set
2✔
174
      else
175
        @pool.length.times{ @queue << :stop }
×
176
      end
177
    end
178

179
    # @!visibility private
180
    def kill_execution
1✔
181
      @queue.clear
×
182
      drain_pool
×
183
    end
184

185
    # Check the thread pool configuration and determine if the pool
186
    # has enought capacity to handle the request. Will grow the size
187
    # of the pool if necessary.
188
    #
189
    # @return [Boolean] true if the pool has enough capacity else false
190
    #
191
    # @!visibility private
192
    def ensure_capacity?
1✔
193
      additional = 0
1,343✔
194
      capacity = true
1,343✔
195

196
      if @pool.size < @min_length
1,343✔
197
        additional = @min_length - @pool.size
73✔
198
      elsif @queue.empty? && @queue.num_waiting >= 1
1,270✔
199
        additional = 0
38✔
200
      elsif @pool.size == 0 && @min_length == 0
1,232✔
201
        additional = 1
×
202
      elsif @pool.size < @max_length || @max_length == 0
1,232✔
203
        additional = 1
1,232✔
204
      elsif @max_queue == 0 || @queue.size < @max_queue
×
205
        additional = 0
×
206
      else
207
        capacity = false
×
208
      end
209

210
      additional.times do
1,343✔
211
        @pool << create_worker_thread
5,904✔
212
      end
213

214
      if additional > 0
1,343✔
215
        @largest_length = [@largest_length, @pool.length].max
1,305✔
216
      end
217

218
      capacity
1,343✔
219
    end
220

221
    # Handler which executes the `overflow_policy` once the queue size
222
    # reaches `max_queue`.
223
    #
224
    # @param [Array] args the arguments to the task which is being handled.
225
    #
226
    # @!visibility private
227
    def handle_overflow(*args)
1✔
228
      case @overflow_policy
×
229
      when :abort
230
        raise RejectedExecutionError
×
231
      when :discard
232
        false
×
233
      when :caller_runs
234
        begin
235
          yield(*args)
×
236
        rescue
237
          # let it fail
238
        end
239
        true
×
240
      end
241
    end
242

243
    # Scan all threads in the pool and reclaim any that are dead or
244
    # have been idle too long. Will check the last time the pool was
245
    # pruned and only run if the configured garbage collection
246
    # interval has passed.
247
    #
248
    # @!visibility private
249
    def prune_pool
1✔
250
      if Time.now.to_f - @gc_interval >= @last_gc_time
1,343✔
251
        @pool.delete_if do |worker|
75✔
252
          worker.dead? ||
128✔
253
            (@idletime == 0 ? false : Time.now.to_f - @idletime > worker.last_activity)
128✔
254
        end
255
        @last_gc_time = Time.now.to_f
75✔
256
      end
257
    end
258

259
    # Reclaim all threads in the pool.
260
    #
261
    # @!visibility private
262
    def drain_pool
1✔
263
      @pool.each {|worker| worker.kill }
×
264
      @pool.clear
×
265
    end
266

267
    # Create a single worker thread to be added to the pool.
268
    #
269
    # @return [Thread] the new thread.
270
    #
271
    # @!visibility private
272
    def create_worker_thread
1✔
273
      wrkr = RubyThreadPoolWorker.new(@queue, self)
5,904✔
274
      Thread.new(wrkr, self) do |worker, parent|
5,904✔
275
        Thread.current.abort_on_exception = false
5,318✔
276
        worker.run
5,318✔
277
        parent.on_worker_exit(worker)
×
278
      end
279
      return wrkr
5,904✔
280
    end
281
  end
282
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc