Class: Oedipus::Connection::Pool

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

Overview

Provides a thread-safe pool of connections, with a specified TTL.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Pool

Initialize a new connection pool with the given options.

Parameters:

  • options (Hash)

    configuration for the pool

  • [String] (Hash)

    a customizable set of options

  • [Fixnum] (Hash)

    a customizable set of options



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/oedipus/connection/pool.rb', line 32

def initialize(options)
  @host = options[:host]
  @port = options[:port]

  @size = options.fetch(:size, 8)
  @ttl  = options.fetch(:ttl, 60)

  @available = []
  @used      = {}
  @expiries  = {}
  @condition = ConditionVariable.new
  @lock      = Mutex.new

  sweeper
end

Instance Method Details

#acquireObject

Acquire a connection from the pool, for the duration of a block.

The release of the connection is done automatically.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/oedipus/connection/pool.rb', line 54

def acquire
  instance = nil
  begin
    @lock.synchronize do
      if instance = @available.pop
        @used[instance] = instance
      elsif @size > (@available.size + @used.size)
        instance = new_instance
      else
        @condition.wait(@lock)
      end
    end
  end until instance

  yield instance
ensure
  release(instance)
end

#disposeObject

Dispose all connections in the pool.

Waits until all connections have finished processing current queries and then releases them.



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/oedipus/connection/pool.rb', line 77

def dispose
  begin
    @lock.synchronize do
      while instance = @available.pop
        instance.close
      end

      @condition.wait(@lock) if @used.size > 0
    end
  end until empty?
end

#empty?Boolean

Returns true if the pool is currently empty.

Returns:

  • (Boolean)

    true if no connections are pooled, false otherwise



93
94
95
# File 'lib/oedipus/connection/pool.rb', line 93

def empty?
  @lock.synchronize { @used.size == 0 && @available.size == 0 }
end