Inconsistently propagating to instance members?

Suppose there is some simple container declared and created this way

class Test {
    private volatile List<Object> list = new ArrayList<>();
}

      

both reading and writing to it are protected by locks; synchronized

the keyword is not used. Although Test.list

declared volatile, none of its member fields, such as ArrayList.elementData

, also have this modifier. Now, in a multithreaded application, will it behave like a floating container? In other words, will the changes submitted by ArrayList.elementData

some thread be immediately visible to all other threads?

+3


source to share


2 answers


The general answer is no volatile

only establishes a relationship between reads and writes to the reference variable. If two threads access the internal field of the object referenced by the variable at the same time, there must still be a synchronization mechanism.



In your case, the best approach seems to be using a synchronized list or some wrapper from a package java.util.concurrent

.

+5


source


The short answer is no. As a consequence, array elements are always non-volatile (even if the array itself is declared volatile). You need to use a custom compatible implementation List

. Usually java.util.concurrent.CopyOnWriteArrayList

meets the needs. If you List

only assign a variable once, then the volatile keyword does not change anything (in which case it is better to use final

).



+2


source







All Articles