Class: MintHttp::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/mint_http/pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Pool

Returns a new instance of Pool.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/mint_http/pool.rb', line 10

def initialize(options = {})
  @mutex = Mutex.new

  @ttl = options[:ttl] || 10000
  @idle_ttl = options[:idle_ttl] || 5000
  @timeout = options[:timeout] || 5000

  @size = options[:size] || 10
  @usage_limit = options[:usage_limit] || 100

  @pool = []
end

Instance Attribute Details

#idle_ttlObject (readonly)

Returns the value of attribute idle_ttl.



5
6
7
# File 'lib/mint_http/pool.rb', line 5

def idle_ttl
  @idle_ttl
end

#sizeObject (readonly)

Returns the value of attribute size.



7
8
9
# File 'lib/mint_http/pool.rb', line 7

def size
  @size
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



6
7
8
# File 'lib/mint_http/pool.rb', line 6

def timeout
  @timeout
end

#ttlObject (readonly)

Returns the value of attribute ttl.



4
5
6
# File 'lib/mint_http/pool.rb', line 4

def ttl
  @ttl
end

#usage_limitObject (readonly)

Returns the value of attribute usage_limit.



8
9
10
# File 'lib/mint_http/pool.rb', line 8

def usage_limit
  @usage_limit
end

Instance Method Details

#acquire(hostname, port, options = {}) ⇒ Object

Raises:

  • (RuntimeError)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/mint_http/pool.rb', line 27

def acquire(hostname, port, options = {})
  namespace = net_factory.client_namespace(hostname, port, options)
  deadline = time_ms + @timeout

  while time_ms < deadline
    @mutex.synchronize do
      if (entry = @pool.find { |e| e.namespace == namespace && e.available? })
        entry.acquire!
        return entry.client
      end

      if @pool.length > 0 && @pool.all? { |e| e.to_clean? }
        clean_pool_unsafe!
      end

      if @pool.length < @size
        client = net_factory.make_client(hostname, port, options)
        entry = append(client, namespace)
        entry.acquire!
        return entry.client
      end
    end

    sleep_time = (deadline - time_ms) / 2
    sleep_time = [sleep_time, 100].max
    sleep_time = sleep_time / 1000.0

    sleep(sleep_time)
  end

  raise RuntimeError, "Cannot acquire lock after #{@timeout}ms."
end

#net_factoryObject



23
24
25
# File 'lib/mint_http/pool.rb', line 23

def net_factory
  @net_factory ||= MintHttp::NetHttpFactory.new
end

#release(client) ⇒ Object

Raises:

  • (ArgumentError)


60
61
62
63
64
65
66
67
68
69
70
# File 'lib/mint_http/pool.rb', line 60

def release(client)
  raise ArgumentError, 'An client is required to be released.' unless client

  @mutex.synchronize do
    if (entry = @pool.find { |e| e.matches?(client) })
      entry.release!
    end

    clean_pool_unsafe!
  end
end