Ruby Threads & ThreadPool
Hello Ruby community !! In this blog , we are going to look into the Thread Pool feature provided by the concurrent-ruby gem. Before jumping into the ThreadPool , let’s first understand why it is needed.
Ruby program usually gets executed in a single thread. Statements in your ruby code gets executed sequentially. For example
api_call_1 # Takes 10 seconds
api_call_2 # Takes 10 seconds
puts "Hello world!!" # Printed after 20 secondsIn the above code, api_call_2 waits until api_call_1 gets finished. Lets assume that api_call_1 and api_call_2 are independant. We can save 10s of our execution time if we make the call to happen in concurrently.
Threads in Ruby
Ruby threads are a lightweight and efficient way to achieve parallelism in your code. When you have multiple unit of work that can happen independently or waiting for external events(I/O bounds) to complete , Ruby thread comes in handy.
We can spin up multiple Threads and assign an unit of work to each thread which can happen in parallel. If we modify our code to run api calls in multiple threads , we can save 10s of execution time.
thread_1 = Thread.new do
api_call_1 # Takes 10 seconds
end
thread_2 = Thread.new do
api_call_2 # Takes 10 seconds
end
# Blocks the main Thread to wait till 2 thread finishes
thread_1.join
thread_2.join
puts "Hello world!!"Wohoo , we reduced the time. Important thing to note here is, both threads didn’t execute in parallel . Both thread started, ran, and completed in overlapping time periods which is called as “Concurrency” .
Advantages of using Threads
- Thread shares the same memory and address space.
- Faster execution .
Disadvantages
- Control can be switched between threads anytime and it can create a chaos and thus leading to race condition.
- Things will go worse if same resource is shared by the multiple Threads. Implementation of locking mechanism (Mutex, Monitor ) is required.
ThreadPool
We can’t keep on creating Threads in our application as it leads to “can’t create Thread: Resource temporarily unavailable” error. We need to limit the number of active threads that can be created by our application and properly manage threads. We can build our own ThreadPool but there are several gems out there which can be used.
Concurrent Ruby
Get Mohan T’s stories in your inbox
Join Medium for free to get updates from this writer.
Concurrent Ruby’s ThreadPool is a simple and easy to use framework which manages the threads and avoids deadlock and race condition problems. We can modify the above example to use concurrent-ruby gem.
require 'benchmark'
require 'concurrent-ruby'
executor = Concurrent::ThreadPoolExecutor.new
executor.post{ api_call_1 }
executor.post{ api_call_2 }Limiting Active Threads using concurrent Ruby
Based on your requirement and system capacity , identify how many active threads needed for you in any given point of time and configure the options. Behind the scenes, concurrent-ruby does all the hard work for you .
pool = Concurrent::ThreadPoolExecutor.new(
min_threads: 5,
max_threads: 10,
max_queue: 10,
fallback_policy: caller_run
)Lets see what these each config options is capable of doing
min_threads
Setting min_threads to 5 will keep on creating threads until it reaches 5. Afterwards if any background job comes, it looks for any active thread which doesn’t have job. If so, it will allocate that job to that thread. Else it create new threads.
max_threads
Setting max_threads to 10 won’t create a new Thread beyond that 10. A new requested task has to wait in the queue until any threads becomes available.
max_queue
Setting max_queue to 100 states that only 100 background jobs can wait in the queue. Any more background job request will be handled based on the fallback_policy settings.
fallback_policy
fallback_policy has 3 options. It is basically what should happen when a new task request comes when queue is full
abort : Silently fail the task .
discard: Raise an exception.
caller_run: Execute in the caller context.
Conclusion
Instead of creating raw threads and managing it, its better to rely on some proven ruby gems which provides ThreadPool feature such as celluloid, workers. Alright! Its cool , isn’t it ? No need to make your application sit idle for I/O Bound. Start a thread in background and execute work while waiting for I/O Bound and improve your application response time.





