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
Array are not immutable.
There's several gems providing thread-safe collection classes in Ruby.
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.
provides several collection classes, such as
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.