Class: Pgbus::ExecutionPools::ThreadPool

Inherits:
Object
  • Object
show all
Defined in:
lib/pgbus/execution_pools/thread_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity:, on_state_change: nil) ⇒ ThreadPool

Returns a new instance of ThreadPool.



10
11
12
13
14
15
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 10

def initialize(capacity:, on_state_change: nil)
  @capacity = capacity
  @on_state_change = on_state_change
  @available_capacity = Concurrent::AtomicFixnum.new(capacity)
  @pool = Concurrent::FixedThreadPool.new(capacity)
end

Instance Attribute Details

#capacityObject (readonly)

Returns the value of attribute capacity.



8
9
10
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 8

def capacity
  @capacity
end

Instance Method Details

#available_capacityObject



32
33
34
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 32

def available_capacity
  @available_capacity.value
end

#idle?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 36

def idle?
  available_capacity.positive?
end

#killObject



48
49
50
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 48

def kill
  @pool.kill
end

#metadataObject



52
53
54
55
56
57
58
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 52

def 
  {
    mode: :threads,
    capacity: @capacity,
    busy: @capacity - available_capacity
  }
end

#post(&block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 17

def post(&block)
  @available_capacity.decrement
  begin
    @pool.post do
      block.call
    ensure
      @available_capacity.increment
      @on_state_change&.call
    end
  rescue StandardError
    @available_capacity.increment
    raise
  end
end

#shutdownObject



40
41
42
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 40

def shutdown
  @pool.shutdown
end

#wait_for_termination(timeout) ⇒ Object



44
45
46
# File 'lib/pgbus/execution_pools/thread_pool.rb', line 44

def wait_for_termination(timeout)
  @pool.wait_for_termination(timeout)
end