Saturday, December 26, 2015

Volatile keyword in Java

Volatile keyword in Java

Volatile keyword gives guarantee that thread won't cache the variables and it can be manipulated by other threads too...



package com.javaetutorial;

import java.util.Scanner;

class Processor extends Thread {

     private static volatile boolean running = true;
/* if running is not volatile, there might come a scenario where while loops keeps running and won't take latest value of running being changed using shutdown() method.
To give guarantee, we make running as volatile which means that thread while running will pick the latest value and variable will get store in main memory and not in thread cache memory.

*/
     public void run() {
           while (running) {
                System.out.println("Hello");
                try {
                     Thread.sleep(200);
                } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                }
           }
     }

     public void shutdown() {
           running = false;
     }
}

public class VolatileKey {

     public static void main(String[] args) {
           Processor pr = new Processor();
           pr.start();

           System.out.println("Press Enter to Stop");
           Scanner scanner = new Scanner(System.in);
           scanner.nextLine();
           pr.shutdown();
     }
}

  
Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory.

The volatile keyword is used to mark a variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

The volatile keyword is used to say to the JVM "Warning, this variable may be modified in another Thread".

Before we move on ,let’s take a look at two important features of locks and synchronization.
1.     Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time.
2.     Visibility: It means that changes made by one thread to shared data are visible to other threads.


Java’s synchronized keyword guarantees both mutual exclusion and visibility. If we make the blocks of threads that modifies the value of shared variable synchronized only one thread can enter the block and changes made by it will be reflected in the main memory. All other thread trying to enter the block at the same time will be blocked and put to sleep.

In some cases we may only desire the visibility and not atomicity. Use of synchronized in such situation is an overkill and may cause scalability problems. Here volatile comes to the rescue. Volatile variables have the visibility features of synchronized but not the atomicity features. The values of volatile variable will never be cached and all writes and reads will be done to and from the main memory.

Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile keyword forces the thread to update the original variable for each variable.

Points to remember

1.     The volatile keyword could be used on every kind of variable, either primitive or objects.

2. A variable can use final or volatile modifier at a single time.

No comments:

Post a Comment