Class: RandomPort::Pool
- Inherits:
-
Object
- Object
- RandomPort::Pool
- Defined in:
- lib/random-port/pool.rb
Overview
Pool of TPC ports.
Use it like this:
RandomPort::Pool.new.acquire do |port|
# Use the TCP port. It will be returned back
# to the pool afterwards.
end
The class is thread-safe, by default. You can configure it to be not-thread-safe, using optional sync argument of the constructor.
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2018 Yegor Bugayenko
- License
-
MIT
Constant Summary collapse
- SINGLETON =
Application wide pool of ports
Pool.new
Instance Method Summary collapse
-
#acquire ⇒ Object
Acquire a new random TCP port.
-
#count ⇒ Object
How many ports acquired now?.
-
#empty? ⇒ Boolean
Is it empty?.
-
#initialize(sync: false) ⇒ Pool
constructor
A new instance of Pool.
-
#release(port) ⇒ Object
Return it back to the pool.
Constructor Details
#initialize(sync: false) ⇒ Pool
Returns a new instance of Pool.
45 46 47 48 49 |
# File 'lib/random-port/pool.rb', line 45 def initialize(sync: false) @ports = [] @sync = sync @monitor = Monitor.new end |
Instance Method Details
#acquire ⇒ Object
Acquire a new random TCP port.
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/random-port/pool.rb', line 65 def acquire loop do server = TCPServer.new('127.0.0.1', 0) port = server.addr[1] server.close next if @ports.include?(port) safe { @ports << port } return port unless block_given? begin return yield port ensure safe { @ports.delete(port) } end end end |
#count ⇒ Object
How many ports acquired now?
55 56 57 |
# File 'lib/random-port/pool.rb', line 55 def count @ports.count end |
#empty? ⇒ Boolean
Is it empty?
60 61 62 |
# File 'lib/random-port/pool.rb', line 60 def empty? @ports.empty? end |
#release(port) ⇒ Object
Return it back to the pool.
82 83 84 |
# File 'lib/random-port/pool.rb', line 82 def release(port) safe { @ports.delete(port) } end |