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

jdantonio / concurrent-ruby / #740

23 May 2014 08:08PM UTC coverage: 81.072% (-16.2%) from 97.237%
#740

push

jdantonio
Merge pull request #96 from jdantonio/refactor/errors

Moved all custom errors into a single file and into the Concurrent module

17 of 18 new or added lines in 10 files covered. (94.44%)

466 existing lines in 32 files now uncovered.

2283 of 2816 relevant lines covered (81.07%)

472.41 hits per line

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

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

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

90
      init_executor
87✔
91

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

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

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

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

117
    # Number of tasks that may be enqueued before reaching `max_queue` and rejecting
1✔
UNCOV
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
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
1✔
UNCOV
126
    #
×
127
    # This method is deprecated and will be removed soon.
128
    def status
129
      warn '[DEPRECATED] `status` is deprecated and will be removed soon.'
130
      mutex.synchronize { @pool.collect { |worker| worker.status } }
131
    end
132

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

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

×
156
    protected
157

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

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

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

1✔
UNCOV
185
    # Check the thread pool configuration and determine if the pool
×
UNCOV
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?
193
      additional = 0
194
      capacity = true
195

196
      if @pool.size < @min_length
1✔
197
        additional = @min_length - @pool.size
3,499✔
198
      elsif @queue.empty? && @queue.num_waiting >= 1
3,499✔
199
        additional = 0
200
      elsif @pool.size == 0 && @min_length == 0
3,499✔
201
        additional = 1
67✔
202
      elsif @pool.size < @max_length || @max_length == 0
3,432✔
203
        additional = 1
1,873✔
204
      elsif @max_queue == 0 || @queue.size < @max_queue
1,559✔
UNCOV
205
        additional = 0
×
206
      else
1,559✔
207
        capacity = false
60✔
208
      end
1,499✔
209

1,499✔
210
      additional.times do
UNCOV
211
        @pool << create_worker_thread
×
212
      end
213

214
      if additional > 0
3,499✔
215
        @largest_length = [@largest_length, @pool.length].max
194✔
216
      end
217

218
      capacity
3,499✔
219
    end
127✔
220

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

×
243
    # Scan all threads in the pool and reclaim any that are dead or
UNCOV
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
250
      if Time.now.to_f - @gc_interval >= @last_gc_time
251
        @pool.delete_if do |worker|
252
          worker.dead? ||
253
            (@idletime == 0 ? false : Time.now.to_f - @idletime > worker.last_activity)
254
        end
1✔
255
        @last_gc_time = Time.now.to_f
3,499✔
256
      end
76✔
257
    end
104✔
258

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

267
    # Create a single worker thread to be added to the pool.
1✔
UNCOV
268
    #
×
UNCOV
269
    # @return [Thread] the new thread.
×
270
    #
271
    # @!visibility private
272
    def create_worker_thread
273
      wrkr = RubyThreadPoolWorker.new(@queue, self)
274
      Thread.new(wrkr, self) do |worker, parent|
275
        Thread.current.abort_on_exception = false
276
        worker.run
277
        parent.on_worker_exit(worker)
1✔
278
      end
194✔
279
      return wrkr
194✔
280
    end
194✔
281
  end
194✔
UNCOV
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