Thread-safe collections in Ruby

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.

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.

Henning Koch About 9 years ago