0

I'm using Concurrent::ThreadLocalVar from concurrent-ruby.

Is it okay to mutate the value like this:

numbers = Concurrent::ThreadLocalVar.new([])
numbers.value # => []
numbers.value.append(1)
numbers.value # => [1]

Or should I reassign the value? Like this:

numbers = Concurrent::ThreadLocalVar.new([])
numbers.value # => []
numbers.value = numbers.value.append(1)
numbers.value # => [1]
Kris
  • 19,188
  • 9
  • 91
  • 111

1 Answers1

0

You can mutate the array in place, as long as you make sure to not "move" a reference to it across thread-boundaries. That is, as long as you access the value only from a single thread (i.e. the same thread with which you got the value) things will be fine.

If you need to access the array from multiple threads concurrently, you likely should use a different abstraction, such as explicit locking with a Thread::Mutex or by using a Concurrent::Array.

In any case, you must always be careful when accessing objects within different threads to ensure concurrent access is safe. If in doubt, try to avoid moving mutable (i.e. non-frozen) objects across thread-boundaries.

Holger Just
  • 52,918
  • 14
  • 115
  • 123