Class: Sequel::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel/connection_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size = 4, &block) ⇒ ConnectionPool

Returns a new instance of ConnectionPool.



9
10
11
12
13
14
15
16
17
# File 'lib/sequel/connection_pool.rb', line 9

def initialize(max_size = 4, &block)
  @max_size = max_size
  @mutex = Mutex.new
  @connection_proc = block

  @available_connections = []
  @allocated = {}
  @created_count = 0
end

Instance Attribute Details

#allocatedObject (readonly)

Returns the value of attribute allocated.



7
8
9
# File 'lib/sequel/connection_pool.rb', line 7

def allocated
  @allocated
end

#available_connectionsObject (readonly)

Returns the value of attribute available_connections.



7
8
9
# File 'lib/sequel/connection_pool.rb', line 7

def available_connections
  @available_connections
end

#connection_procObject

Returns the value of attribute connection_proc.



6
7
8
# File 'lib/sequel/connection_pool.rb', line 6

def connection_proc
  @connection_proc
end

#created_countObject (readonly)

Returns the value of attribute created_count.



7
8
9
# File 'lib/sequel/connection_pool.rb', line 7

def created_count
  @created_count
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



5
6
7
# File 'lib/sequel/connection_pool.rb', line 5

def max_size
  @max_size
end

#mutexObject (readonly)

Returns the value of attribute mutex.



5
6
7
# File 'lib/sequel/connection_pool.rb', line 5

def mutex
  @mutex
end

Instance Method Details

#acquire(thread) ⇒ Object



42
43
44
45
46
# File 'lib/sequel/connection_pool.rb', line 42

def acquire(thread)
  @mutex.synchronize do
    @allocated[thread] = available
  end
end

#availableObject



48
49
50
# File 'lib/sequel/connection_pool.rb', line 48

def available
  @available_connections.pop || make_new
end

#holdObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sequel/connection_pool.rb', line 23

def hold
  t = Thread.current
  if (conn = owned_connection(t))
    return yield(conn)
  end
  while !(conn = acquire(t))
    sleep 0.001
  end
  begin
    yield conn
  ensure
    release(t)
  end
end

#make_newObject



52
53
54
55
56
57
# File 'lib/sequel/connection_pool.rb', line 52

def make_new
  if @created_count < @max_size
    @created_count += 1
    @connection_proc.call
  end
end

#owned_connection(thread) ⇒ Object



38
39
40
# File 'lib/sequel/connection_pool.rb', line 38

def owned_connection(thread)
  @mutex.synchronize {@allocated[thread]}
end

#release(thread) ⇒ Object



59
60
61
62
63
64
# File 'lib/sequel/connection_pool.rb', line 59

def release(thread)
  @mutex.synchronize do
    @available_connections << @allocated[thread]
    @allocated.delete(thread)
  end
end

#sizeObject



19
20
21
# File 'lib/sequel/connection_pool.rb', line 19

def size
  @created_count
end