Blog Image

Java Volatile Keyword  

Volatile is the famous area in Multi-Threading in Java. Most of the programmers don't have clear understanding of Volatile Keyword. This blogs explains about the Volatile Keyword and how to use it with an example, and where is it applicable.

Volatile Keyword

Volatile keyword in Java is used as an indicator to Java Compiler and Thread Not to store the value in CPU cache and always read it from Main Memory only, it is in short ?Always in main memory?

Java volatile keyword Guarantee Visibility.

Java volatile visibility

In a Multi-Threaded environment, a Thread copies the variable value from Main Memory to the CPU Cache for performance optimization. If multiple Threads are running, each thread copies the same variable value into its local CPU cache (also called as Working Memory) as shown below.


 In this case there is no guarantee when does the read or write operations of CPU cache value will be written into the Main Memory variable this leads to in-consistency issues. For e.g.. if Thread#1 modifies the ?I? value from ?0? to ?10? it only changes the value in its CPU cache only and Thread#2 will not be able to see its changes.

If you make the variable ?I? as volatile Java ensures such read/write operations to the variable are directly been done on to the Main Memory. This guarantees the Visibility of the Variable to all the other Threads.

Java Volatile Guarantee Read/Write Before

Since Java 5 the volatile keyword guarantees more than just reading and writing to the main memory.

      If Thread#1 writes to a volatile variable and Thread#2 subsequently reads from the volatile variable then all the variables visible to Thread#1 before writing to the volatile variable will also be visible to Thread#2 after reading from volatile variable.

For e.g. if Thread#1 tries to write to a non-volatile and volatile variables as shown below.


sharedObject.nonVolatileVariable = 100
sharedObject.volatileVariable = 200

then all the writes to the variable before the volatile also will be written to the Main Memory (including non-volatile variables)

When Thread#2 tries reading the volatile variable then all the variables before the volatile read will be fetched from Main Memory only.

This states that all the variables in your object are not necessarily required to declare as volatile.

      The reading and writing instructions of volatile variables cannot be reordered by the JVM. JVM usually reorder the instructions for performance reasons as long as the JVM detects no change in the program behavior if it reorders.

Following example shows usage of volatile keyword

package com.sjg.vol;
public class TrafficManager {
    protected static int changeInterval = 5;
    protected static volatile int clock = 0;

    public static void main(String[] args) {
        new TrafficSignal().start();
        new TrafficTimer().start();
    }

    private static final class TrafficSignal extends Thread {
        public void run() {
            // copy the clock to local variable and compare it reached to change
            // interval or not
            int localClock = clock;
            while (localClock < changeInterval) {
                // when there is a change in time i want to copy that time into
                // local variable
                if (localClock != clock) {
                    System.out.println("clock : " + clock);
                    localClock = clock;
                }
            }
            // change the signal color
            System.out.println("chaning the signal color as interval reached");

        }
    }

    private static final class TrafficTimer extends Thread {
        public void run() {
            int localClock = clock;
            while (clock < changeInterval) {
                System.out.println("changing clock : " + localClock);
                clock = ++localClock;
                try {
                    Thread.sleep(500L);
                } catch (Exception e) {
                    // eat it
                }
            }
        }
    }
}



In the above program I have shared variable "clock" TrafficTimer Thread is incrementing the variable till changeInterval. TrafficSignal Thread changes the Signal Color if the Clock reaches to the changeInterval. If you didn't declared the "clock" as volatile the TrafficTimer Thread modifications to  "clock" variable will not be visible to TrafficSignal Thread.

Please refer to the Volatile.zip file attached to this blog for reference.

Volatile is enough?

Even volatile variable guarantees all reads are done from Main Memory and all writes are done from Main Memory, this is not enough. You need to use Synchronized to guarantee the read/write operations to be atomic.

About author

User Image
Sriman

A software developer on JDK and JEE platform. I am passionate about Java technology and always an explorer and learner in new technologies in Java. I have experience on Open Source technologies like Struts, Spring, Jsf etc.. and even strong knowledge on Integration/Distributed world like Ejb, Web Services and Restful Services.

10

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      Ranjith3177
      17-12-2017 08:51:40 AM

    It is very easy understanding and useful. Thanks...

  • author image
    by:
      ali032
      13-12-2017 06:46:16 PM

    Thanks a lot for sharing this valuable content and make us clear understanding about the volatile keyword...

  • author image
    by:
      mahendhar
      13-12-2017 04:31:39 AM

    Thanq very much for posting this....................

  • author image
    by:
      madhup
      12-12-2017 06:39:52 PM

    Thanks for writing this block clearly understanding the volatile keyword

  • author image
    by:
      Ramana97
      12-12-2017 05:29:43 PM

    thanks for writing this bolg.it is so useful for us

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.