Understanding volatile in java
To understand volatile, first you have to understand a little something about the Java memory model.
What is happens-before relation?
volatile’s job is to guarantee “happens-before” behavior. This means three things:
The keyword volatile will not perform any mutual exclusive lock on the variable. Most recent value is ensured because it ignores caching. So if a variable is declared volatile, it takes the value from the main memory, rather than cache and delivers the recent value or latest value.
To understand volatile, first you have to understand a little something about the Java memory model.
- Each thread in Java takes place in a separate memory space, I mean its personal stack, but various threads share memory among them.
- You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.
- Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication (i.e. using locks on the shared data), you can't guarantee which writes get seen by other threads, or even the order in which they get seen.
What is happens-before relation?
volatile’s job is to guarantee “happens-before” behavior. This means three things:
- Write operations are executed before read operations.
- Compilers are not allowed to re-order accesses to the field.
- Caches must be flushed before reading the field
The keyword volatile will not perform any mutual exclusive lock on the variable. Most recent value is ensured because it ignores caching. So if a variable is declared volatile, it takes the value from the main memory, rather than cache and delivers the recent value or latest value.
As of Java 5 write access to a volatile variable will also update non-volatile variables which were modified by the same thread. This can also be used to update values within a reference variable, e.g. for a volatile variable person. In this case you must use a temporary variable person and use the setter to initialize the variable and then assign the temporary variable to the final variable. This will then make the address changes of this variable and the values visible to other threads.
Difference between volatile in old and new Java Memory Model
Old java volatile | New java volatile |
A volatile variable cannot be cached. | (same) |
A volatile variable cannot be reordered with another variable but may be reordered with volatile variable. | A volatile variable cannot be reordered. (notice the change) |
Volatile observes happens-before-relationship. |
- happens-before-relationship.(soon to be posted)
- Difference between synchronized and volatile
No comments:
Post a Comment