Java Reference
In-Depth Information
Java Memory Model (JMM)
All program variables (instance fields, static fields, and array elements) in a program are allocated memory on the
main memory of a computer. Each thread has a working memory (processor cache or registers). JMM describes how,
when and in what order program variables are stored to, and read from, the main memory. JMM is described in the
Java Language Specification in detail. You may visualize JMM as depicted in Figure 6-5 .
Thread-1
Thread-2
Main memory
Object-1
Object-2
Object-3
Working
memory
Working
memory
Figure 6-5. Java Memory model
Figure 6-5 shows two threads sharing the main memory. Let's assume that you have a Java program that is
running two threads, thread-1 and thread-2, and each thread is running on different processors. Suppose thread-1
reads the value of an instance variable of object-1 in its working memory, updates the value, and does not write the
updated value back to the main memory. Let's run through some possible scenarios.
What happens if thread-2 tries to read the value of the same instance variable of object-1 from
the main memory? Would thread-2 read the old value from the main memory, or would it be
able to read the updated value from the working memory of thread-2?
Suppose thread-1 is in the middle of writing the updated value to the main memory, and
at the same time, thread-2 is trying to read the same value from the main memory. Would
thread-2 read the old value or some garbage value from the main memory because the value is
not written back to the main memory completely?
JMM answers all such questions. In essence, JMM describes three important aspects of the execution of
instructions in a Java program. They are as follows:
Atomicity
Visibility
Ordering
Atomicity
JMM describes actions that should be executed atomically. It describes atomicity rules about read and write actions
on instance variables, static variables, and array elements. It guarantees that read and write on an object's field of
any type, except long and double , are always atomic. However, if a field of type long or double is declared volatile
(I will discuss the volatile keyword in detail later in this chapter), read and write on that field are also guaranteed
to be atomic.
 
 
Search WWH ::




Custom Search