Read more

Thread-safe collections in Ruby

Henning Koch
April 15, 2015Software engineer at makandra GmbH

When using threads, you must make your code thread-safe. This can be done by either locking (mutexes) all data shared between threads, or by only using immutable data structures. Ruby core classes like String or Array are not immutable.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

There are several gems providing thread-safe collection classes in Ruby.

concurrent-ruby

The concurrent-ruby Show archive.org snapshot gem provides thread-safe versions of Array and Hash:

sa = Concurrent::Array.new # supports standard Array.new forms
sh = Concurrent::Hash.new # supports standard Hash.new forms

There's also a Concurrent::Cache class that sort of behaves like an unordered Hash, but is much faster.

Info

If you're using Rails you already have concurrent-ruby in your bundle.

hamster

hamster Show archive.org snapshot provides several collection classes, such as Hamster::Hash.

Hamster collections are immutable. Whenever you modify a Hamster collection, the original is preserved and a modified copy is returned. This makes them inherently thread-safe and shareable. At the same time, they remain CPU and memory-efficient by sharing between copies.

Posted by Henning Koch to makandra dev (2015-04-15 11:34)