Posted over 4 years ago. Visible to the public. Repeats.

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's several gems providing thread-safe collection classes in Ruby.

concurrent-ruby

The concurrent-ruby gem provides thread-safe versions of Array and Hash:

Copy
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.

hamster

hamster 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
13 days ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more