Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

volatile keyword in java

if we declare a variable volatile then the value of this variable will never be cached thread-locally and all reads and writes will go straight to "main memory". Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

 When is volatile enough?

If two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use synchronization in that case to guarantee that the reading and writing of the variable is atomic.

But in case one thread reads and writes the value of a volatile variable, and other threads only read the variable, then the reading threads are guaranteed to see the latest value written to the volatile variable. Without making the variable volatile, this would not be guaranteed.

 volatile enhancement in Java 5.0

Up to Java 4 volatile could be re-ordered by compiler with respect to any previous read or write, leading to subtle concurrency bugs e.g. making it impossible to implement a double check locking (very common idiom for a Singleton).

This is fixed in Java 5.0 which extends the semantics for volatile which cannot be reordered with respect to any following read or write anymore and introduces a new memory model. volatile-jmm

double checked locking with volatile
 Important points on Volatile keyword in Java

 1. The volatile keyword in Java is only application to a variable not class and method.

 2. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

 3. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

 4. In Java reads and writes are atomic.

 5. write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

 6. Java volatile variable that is an object reference may be null.