# Thread safety in Ruby applications

Source: https://www.ironin.it/blog/thread-safety-ruby-applications.html

Published 29 April 2020

[security](https://www.ironin.it/blog/tags/security) [multithreading](https://www.ironin.it/blog/tags/multithreading) [ruby](https://www.ironin.it/blog/tags/ruby) [web](https://www.ironin.it/blog/tags/web)

![Thread safety in Ruby applications](https://www.ironin.it/api/media/file/ironin-seed-ZjRjMDhlN2UtZjU1My00NDFiLWJlZDMtODFlMzYwMjBmNmU4_header.jpg)

Multithreading is the ability to execute code on multiple concurrent threads. Each thread exists within a process, and each process can have at least one thread. Multithreading allows you to speed up your program but creates additional problems that do not occur in single-threaded programs. If you use multiple threads in your app, you must ensure your code is thread-safe. Below are examples prepared by experts from iRonin, a top [Ruby on Rails development company](https://www.ironin.it/services/ruby-on-rails-development).

Let's start with this simple program.

```ruby
# program.rb
    
    class Program
      def self.call; new.call; end
    
      def call
        number = 1
        100.times { number += number }
        number
      end
    end
```

And a test for it to make sure everything works properly.

```ruby
# program_spec.rb
    
    require './program'
    
    describe Program do
      it { expect(described_class.call).to eq(1267650600228229401496703205376) }
    end
```

Time to run our test.

```ruby
$ rspec program_spec.rb
    .
    
    Finished in 0.02662 seconds (files took 1.12 seconds to load)
    1 example, 0 failures
```

Success! Our program passed the test. Now, let's see what the result will be with two threads. To create a new thread, we will use the Thread class, which is an abstraction for an operating system thread. When you create a Thread, you must pass the code block executed inside the thread. We have to call the join method on each thread to ensure that the main thread will wait for our threads to finish.

```ruby
# program.rb
    
    class Program
      def self.call; new.call; end
    
      def call
        number = 1
        2.times.map do
          Thread.new { 500.times { number += number }}
        end.each(&:join)
        number
      end
    end
```

Let's run our test.

```ruby
$ rspec program_spec.rb
    .
    
    Finished in 0.02662 seconds (files took 1.12 seconds to load)
    1 example, 0 failures
```

Alright, it looks like everything works well. But let's run the same example with JRuby.

```ruby
$ rspec program_spec.rb
    F
    
    Failures:
    
      1) Program should eq 1267650600228229401496703205376
         Failure/Error: it { expect(described_class.call).to eq(1267650600228229401496703205376) }
    
           expected: 1267650600228229401496703205376
                got: 14855280471424563298789490688
    
           (compared using ==)
         # ./program_spec.rb:4:in `block in (root)'
    
    Finished in 0.04002 seconds (files took 1.12 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./program_spec.rb:4 # Program should eq 1267650600228229401496703205376
```

Oops, that's not what we expected! What's going on? What you see above happened because, unlike with MRI (Matz's Ruby Interpreter), there is no GIL (Global Interpreter Lock) mechanism in JRuby. The GIL ensures that two threads cannot be executed at the same time. That means threads on MRI won't run in parallel - MRI just switches between threads, giving each some CPU time. To fix our code so it works with JRuby, we can use the Mutex locking system, which will allow synchronization access to specific code sections.

```ruby
# program.rb
    
    class Program
      def self.call; new.call; end
    
      def call
        number = 1
        mutex = Mutex.new
        2.times.map do
          Thread.new do
            500.times { mutex.synchronize { number += number }}
          end
        end.each(&:join)
        number
      end
    end
```

Let's check if it works.

```ruby
$ rspec program_spec.rb
    .
    
    Finished in 0.02662 seconds (files took 1.12 seconds to load)
    1 example, 0 failures
```

Ok, fixed. Does that mean you don't have to care about thread safety when you have GIL? Well, not really. Imagine a situation in which you read some global resource and update its value after a while. We can simulate this with the following example:

```ruby
# program.rb
    
    class Program
      def self.call; new.call; end
    
      def call
        number = 1
        2.times.map do
          Thread.new do
            50.times do
              number_value = number
              sleep(0.001)
              number += number_value
            end
          end
        end.each(&:join)
        number
      end
    end
```

Now, let's run that with MRI.

```ruby
$ rspec program_spec.rb
    F
    
    Failures:
    
      1) Program should eq 1267650600228229401496703205376
         Failure/Error: it { expect(described_class.call).to eq(1267650600228229401496703205376) }
    
           expected: 1267650600228229401496703205376
                got: 1525719740468429782208
    
           (compared using ==)
         # ./program_spec.rb:4:in `block (2 levels) in <top (required)>'
    
    Finished in 0.07984 seconds (files took 0.28282 seconds to load)
    1 example, 1 failure
    
    Failed examples:
    
    rspec ./program_spec.rb:4 # Program should eq 1267650600228229401496703205376
```

As we can see, GIL does not ensure that our code is always thread-safe. We need to make sure that all operations are atomic. We do that by using the exact mechanism as before - Mutex.

```ruby
# program.rb
    
    class Program
      def self.call; new.call; end
    
      def call
        number = 1
        mutex = Mutex.new
        2.times.map do |i|
          Thread.new do
            50.times do
              mutex.synchronize do
                number_value = number
                sleep(0.001)
                number += number_value
              end
            end
          end
        end.each(&:join)
        number
      end
    end
```

If you use threads, you must ensure that your code and any gem are thread-safe. Special care should be taken if you use a background processing system like Sidekiq. By default, one Sidekiq process creates 10 threads. You can change that by changing the concurrency value in the Sidekiq config file.

Share:

[Let’s get in touch](https://www.ironin.it/contact-us.html)

Author: Kamil Szubrycht

Need software like this built?

[Software development →](https://www.ironin.it/ai-software-engineering)

Our code is merged into 10 open-source AI-agent projects, two of them with tens of thousands of GitHub stars.

[Talk to us →](https://www.ironin.it/contact-us.html?offer=ai-software-engineering)

## Read similar articles

- [Ruby on Rails vs Django in-depth comparison. Picking the Best Web Development Framework for 2025](https://www.ironin.it/blog/ruby-on-rails-vs-django-comparison.html)
- [Intro to Arel - the database agnostic SQL](https://www.ironin.it/blog/intro-to-arel-the-database-agnostic-sql.html)
- [Docker 101](https://www.ironin.it/blog/docker-101.html)
- [Ruby 3.4.0 Release - What's New and How Does It Impact Your Project?](https://www.ironin.it/blog/ruby-3.4-release-tech-and-business-impact.html)

## Read next

- [Which AI model is best for your own task? Our own test and a public leaderboard disagreed](https://www.ironin.it/blog/own-ai-model-evals.html)
- [What uses up a Claude plan's usage limit? What each kind of token costs against it](https://www.ironin.it/blog/claude-usage-limit-token-costs.html)
- [Identity and payments in modern world. How our client Bitt is changing the world?](https://www.ironin.it/blog/identity-and-payments.html)
