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

ruby-concurrency / concurrent-ruby / #2872

08 Jun 2014 06:00PM UTC coverage: 77.573% (-11.7%) from 89.319%
#2872

push

jdantonio
Updated badges with new repo location.

2186 of 2818 relevant lines covered (77.57%)

527.3 hits per line

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

75.86
/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 RubyExecutor
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
180✔
81
      @max_length = opts.fetch(:max_threads, DEFAULT_MAX_POOL_SIZE).to_i
180✔
82
      @idletime = opts.fetch(:idletime, DEFAULT_THREAD_IDLETIMEOUT).to_i
180✔
83
      @max_queue = opts.fetch(:max_queue, DEFAULT_MAX_QUEUE_SIZE).to_i
180✔
84
      @overflow_policy = opts.fetch(:overflow_policy, :abort)
180✔
85

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

90
      init_executor
180✔
91

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

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

102
    def can_overflow?
1✔
103
      @max_queue != 0
×
104
    end
105

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

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

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

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

137
    # Run on task completion.
138
    #
139
    # @!visibility private
140
    def on_end_task
1✔
141
      mutex.synchronize do
1,336✔
142
        @completed_task_count += 1 #if success
1,336✔
143
        break unless running?
1,336✔
144
      end
145
    end
146

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

160
    protected
1✔
161

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

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

183
    # @!visibility private
184
    def kill_execution
1✔
185
      @queue.clear
×
186
      drain_pool
×
187
    end
188

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

200
      if @pool.size < @min_length
1,357✔
201
        additional = @min_length - @pool.size
98✔
202
      elsif @queue.empty? && @queue.num_waiting >= 1
1,259✔
203
        additional = 0
27✔
204
      elsif @pool.size == 0 && @min_length == 0
1,232✔
205
        additional = 1
×
206
      elsif @pool.size < @max_length || @max_length == 0
1,232✔
207
        additional = 1
1,232✔
208
      elsif @max_queue == 0 || @queue.size < @max_queue
×
209
        additional = 0
×
210
      else
211
        capacity = false
×
212
      end
213

214
      additional.times do
1,357✔
215
        @pool << create_worker_thread
7,504✔
216
      end
217

218
      if additional > 0
1,357✔
219
        @largest_length = [@largest_length, @pool.length].max
1,330✔
220
      end
221

222
      capacity
1,357✔
223
    end
224

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

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

264
    # Reclaim all threads in the pool.
265
    #
266
    # @!visibility private
267
    def drain_pool
1✔
268
      @pool.each {|worker| worker.kill }
×
269
      @pool.clear
×
270
    end
271

272
    # Create a single worker thread to be added to the pool.
273
    #
274
    # @return [Thread] the new thread.
275
    #
276
    # @!visibility private
277
    def create_worker_thread
1✔
278
      wrkr = RubyThreadPoolWorker.new(@queue, self)
7,504✔
279
      Thread.new(wrkr, self) do |worker, parent|
7,504✔
280
        Thread.current.abort_on_exception = false
6,476✔
281
        worker.run
6,476✔
282
        parent.on_worker_exit(worker)
×
283
      end
284
      return wrkr
7,504✔
285
    end
286
  end
287
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