To demonstrate a thread safe implementation of a connection pool, we will use a class instance variable, a Mutex, and the connection_pool gem.
Class instance variables work like regular class variables except for two main differences.
We will use class instance variables (mainly for reason 1) to share a connection pool which all threads will be able to access. Here is a quick example of what class instance variables can do for us.
class Example
@my_value = 1
class << self
# class methods
def my_value
@my_value
end
def my_value=(value)
@my_value = value
end
end
# instance methods
def my_value
@my_value
end
def my_value=(value)
@my_value = value
end
end
# class method
puts Example.my_value # my_value = 1
Example.my_value = 2
puts Example.my_value # my_value = 2
# instance method
a = Example.new
puts a.my_value # my_value is not initialized at the instance level
a.my_value = 3
puts a.my_value # my_value = 3
# class method
puts Example.my_value # my_value is still 2 at the class level
When my_value
was accessed by class methods, its value was only accessed and updated at the class level. When accessed as an instance method, it was accessed and updated in a separate memory space at the instance level.
If you want to learn more about class instance variables, take a look at this article and this post.
Now that we have a way to access the _same _connection pool across threads, we need to actually create the pool so threads can use it.
The connection_pool gem will allow us to create a pool of connections which we can use to grab a connection and return it after we’re done using it. This allows us to specify a static number of connections and forces our threads to share those connections.
#connection-pool #ruby-on-rails #programming #development #ruby