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

ruby-concurrency / concurrent-ruby / #2711

16 Jun 2014 12:13PM UTC coverage: 45.896% (-50.5%) from 96.422%
#2711

push

jdantonio
Merge pull request #112 from ruby-concurrency/remove-old-actor

Remove old Actor

1 of 2 new or added lines in 2 files covered. (50.0%)

1362 existing lines in 62 files now uncovered.

1219 of 2656 relevant lines covered (45.9%)

0.98 hits per line

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

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

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

90
      init_executor
2✔
91

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

98
      @gc_interval = opts.fetch(:gc_interval, 1).to_i # undocumented
2✔
99
      @last_gc_time = Time.now.to_f - [1.0, (@gc_interval * 2.0)].max
2✔
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
133
      warn '[DEPRECATED] `status` is deprecated and will be removed soon.'
×
UNCOV
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✔
142
        @completed_task_count += 1 #if success
1✔
143
        break unless running?
1✔
144
      end
145
    end
146

147
    # Run when a thread worker exits.
148
    #
149
    # @!visibility private
150
    def on_worker_exit(worker)
1✔
UNCOV
151
      mutex.synchronize do
×
UNCOV
152
        @pool.delete(worker)
×
UNCOV
153
        if @pool.empty? && ! running?
×
UNCOV
154
          stop_event.set
×
UNCOV
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✔
165
      if ensure_capacity?
1✔
166
        @scheduled_task_count += 1
1✔
167
        @queue << [args, task]
1✔
168
      else
UNCOV
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
      if @pool.empty?
2✔
176
        stopped_event.set
1✔
177
      else
178
        @pool.length.times{ @queue << :stop }
65✔
179
      end
180
    end
181

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

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

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

213
      additional.times do
1✔
214
        @pool << create_worker_thread
64✔
215
      end
216

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

221
      capacity
1✔
222
    end
223

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

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

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

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