Java Reference
In-Depth Information
14.10. The Memory Model: Synchronization and volatile
Any mutable (that is, changeable) value shared between different
threads should always be accessed under synchronization to prevent in-
terference from occurring. Synchronization comes at a cost, however,
and may not always be necessary to prevent interference. The language
guarantees that reading or writing any variables, other than those of type
long or double , is atomicthe variable will only ever hold a value that was
written by some thread, never a partial value intermixing two different
writes. This means, for example, that an atomic variable that is only writ-
ten by one thread and read by many threads need not have access to it
synchronized to prevent corruption because there is no possibility of in-
terference. This does not help with getmodifyset sequences (such as ++ ),
which always require synchronization.
Atomic access does not ensure that a thread will always read the most
recently written value of a variable. In fact, without synchronization,
a value written by one thread may never become visible to another
thread. A number of factors affect when a variable written by one thread
becomes visible to another thread. Modern multiprocessing hardware
can do very strange things when it comes to the way in which shared
memory values get updated, as can dynamic compilation environments
at runtime. Further, in the absence of synchronization the order in which
variables are seen to be updated by different threads can be completely
different. To the programmer these things are not only strange, they of-
ten seem completely unreasonable and invariably not what the program-
mer wanted. The rules that determine how memory accesses are ordered
and when they are guaranteed to be visible are known as the memory
model of the Java programming language.
The actions of a thread are determined by the semantics of the state-
ments in the methods that it executes. Logically, these statements are
executed in the order the statements are writtenan order known as pro-
gram order. However, the values of any variables read by the thread are
determined by the memory model. The memory model defines the set of
allowed values that can be returned when a variable is read. In this con-
text variables consist only of fields (both static and non-static) and ar-
ray elements. From a programmer's perspective this set of values should
 
Search WWH ::




Custom Search