Let's say I have a shared object with field data
. Multiple threads will share a reference to this object in order to access the field. The threads never access the object concurrently, though. Do I need to declare data
as volatile?
Such a situation would be the following:
- A class
Counter
defines a unique fieldvalue
and one methodincrement
. - A thread increments the counter, then spawn another thread that increments the counter, etc.
Given the very logic of the program, there is no concurrent access to the counter. The counter is however shared accross multiple threads. Must the counter be a volatile?
Another variant of the situation is when multiple threads manipulate an object X that is plain data, but alternate their temporal execution (so that X is never accessed concurrently) via another object Y that rely on concurrency control (wait
, notify
, synchronize
). Should fields of object X be volatile?