Is java – volatile propagated to instance members?
Suppose you have some simple container declarations and instantiate them like this
class Test { private volatile List<Object> list = new ArrayList<>(); }
, read and write are protected by lock; The synchronized keyword is not used Although test List is declared volatile, but all its member fields (such as ArrayList. Elementdata) do not have this modifier Now, in a multithreaded application, will it look like a volatile container? In other words, some threads submit to ArrayList Will changes to elementdata be immediately visible to all other threads?
Solution
The general answer is no: volatile only establishes a prior relationship between reading and writing reference variables If two threads access the internal fields of the object referenced in the variable at the same time, a synchronization mechanism is still required
In your case, the best approach seems to be to use synchronized lists, or Java util. Some wrappers in the concurrent package