Java Reference
In-Depth Information
Because threads share the same memory address space and run concurrently, they can access
or modify variables that other threads might be using. This is a tremendous convenience, be-
cause it makes data sharing much easier than would other inter-thread communications mech-
anisms. But it is also a significant risk: threads can be confused by having data change un-
expectedly. Allowing multiple threads to access and modify the same variables introduces an
element of nonsequentiality into an otherwise sequential programming model, which can be
confusing and difficult to reason about. For a multithreaded program's behavior to be predict-
able, access to shared variables must be properly coordinated so that threads do not interfere
with one another. Fortunately, Java provides synchronization mechanisms to coordinate such
access.
UnsafeSequence can be fixed by making getNext a synchronized method, as
shown in Sequence in Listing 1.2 , [3] thus preventing the unfortunate interaction in Figure
1.1 . (Exactly why this works is the subject of Chapters 2 and 3 .)
Listing 1.2. Thread-safe Sequence Generator.
In the absence of synchronization, the compiler, hardware, and runtime are allowed to take
substantial liberties with the timing and ordering of actions, such as caching variables in re-
gisters or processor-local caches where they are temporarily (or even permanently) invisible
to other threads. These tricks are in aid of better performance and are generally desirable, but
they place a burden on the developer to clearly identify where data is being shared across
threads so that these optimizations do not undermine safety. ( Chapter 16 gives the gory de-
tails on exactly what ordering guarantees the JVM makes and how synchronization affects
those guarantees, but if you follow the rules in Chapters 2 and 3 , you can safely avoid these
low-level details.)
Search WWH ::




Custom Search