1.

Volatile keyword in Java

Answer»

A class can be made thread safe using the volatile keyword. This means that multiple threads can use the class instance or methods at the same time without any problem.

The USAGE of the volatile keyword on a particular variable means the following:

  1. The VALUE of the variable with the volatile keyword is never CACHED thread locally. This means that all the read and write operations on the variable are saved in the main memory.
  2. The access to the variable appears as though it is enclosed in a synchronized block and is synchronized on itself.

An example of the volatile keyword is given as follows:

class Shared {   static volatile int value = 15; }

In the above example, if there are any changes made by one thread then they are reflected in the other threads as WELL using the volatile keyword.

Differences between volatile and synchronized

Some of the differences between volatile and synchronized are given as follows:

Characteristic
volatile
synchronized
Is null allowed?
Yes
No
Variable Type
Object variable or primitive variable
Object variable
When does synchronization occur?
When a volatile variable is accessed
When a synchronized block is explicitly entered or exited.
Are all cached variables synchronized on access?
This is true from Java 5 onwards.
Yes
Can this be used to combine several operations into a single atomic operation?
This is not possible before Java 5 but in Java 5 it is.
Yes


Discussion

No Comment Found