`
jy00509336
  • 浏览: 243502 次
  • 性别: Icon_minigender_1
  • 来自: 山西
社区版块
存档分类
最新评论

How Volatile in Java works ? Example of volatile keyword in Java

 
阅读更多
How to use Volatile keyword in Java
What  is Volatile variable in Java  and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews. Though many programmer knows what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. In this tutorial we will address this gap by providing simple example of volatile variable in Java and discussing some when to use Volatile variable in Java. Any way  Volatile keyword in Java is used as an indicator to Java compiler and  Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like AutoboxingEnumGenerics and Variable arguments ,  Java introduces some change in Java Memory Model (JMM),  Which  guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.
 
 
This Java tutorial on Volatile keyword is in continuation of my article How HashMap works in Java  and difference between HashMap and Hashtable in Java  , How Garbage collection works in Java and How Synchronization works in Java if you haven’t read already you may find some useful information based on my experience in Java .

 

 
 
Example of volatile keyword in Java:
To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.
 
/**
 * Java program to demonstrate where to use Volatile keyword in Java.
 * In this example Singleton Instance is declared as volatile variable to ensure
 * every thread see updated value for _instance.
 * 
 * @author Javin Paul
 */

public class Singleton{
private static volatile Singleton _instance; //volatile variable 

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}
 
If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.
 
If we do not make _instance variable volatile then Thread which is creatininstance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.
 
 
Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.
 
So in Summary apart from synchronized keyword in javavolatile keyword is also used to communicate content of memory between threads.
 
Let’s see another example of volatile keyword in Java:
Volatile variable example in Javamost of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't  use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value ofvolatile variable will always be read from main memory  and  "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.
 
 private boolean bExit;

 while(!bExit) {
    checkUserPosition();
    updateUserPosition();
 }
 
In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.
 
 

When to use Volatile variable in Java

One of the most important thing in learning of volatile keyword is understanding when to use volatile variable in Java. Many programmer knows what is volatile variable and How does it work but they never really used volatile for any practical purpose. Here are couple of example to demonstrate when to use Volatile keyword in Java:
 
1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many  platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.
 
2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values.
 
3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop
 
private boolean isActive = thread;
public void printMessage(){
  while(isActive){
     System.out.println("Thread is Active");
  }
} 
 
without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.
 
4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.
 
Important points on Volatile keyword in Java
1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.
 
2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
 
3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
 
4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
 
5. From Java 5 changes to a volatile variable are always visible to other threads. What’s more it also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.
 
6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java.
 
7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.
 
8. Java volatile variable that is an object reference may be null.
 
9. Java volatile keyword doesn't means 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.
 
10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.
 
 
Difference between synchronized and volatile keyword in Java
Difference between volatile and synchronized is another popular core Java question asked in multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.
 
1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods.
 
2. Synchronized obtains and releases lock on monitor’s java volatile keyword doesn't require that.
 
3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java.
 
4. Synchronized method affects performance more than volatile keyword in Java.
 
5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory  and "main" memory  while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.
 
6. You can not synchronize on null object but your volatile variable in java could be null.
 
7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire
 
In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java
 
if you like to know more about volatile I would also suggest to go thorough FAQ on Java Memory Model here which explains happens-before operations quite well.
 
Other Java concurrency tutorials from Javarevisited you may like



Read more: http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html#ixzz39aa6kWTX

分享到:
评论

相关推荐

    18Java内存模型:Java中的volatile有什么用?1

    Java内存模型(JVM Memory Model,简称JMM)是Java语言规范中定义的一个抽象概念,它描述了在多线程环境下,各个线程之间共享变量的访问规则,以及在并发情况下如何保证数据的一致性。Java内存模型的主要目标是解决...

    java volatile 关键字实战

    java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java volatile 关键字实战java ...

    Java线程:volatile关键字

    Java 线程 volatile 关键字详解 Java™ 语言包含两种内在的同步机制:同步块(或方法)和 volatile 变量。volatile 变量的同步性较差,但它有时更简单并且开销更低。volatile 变量可以被看作是一种 “程度较轻的 ...

    Java并发编程:volatile关键字解析

    ### Java并发编程:volatile关键字解析 #### 一、内存模型的相关概念 在深入了解`volatile`关键字之前,我们首先需要理解计算机内存模型的一些基本概念。在现代计算机系统中,CPU为了提高执行效率,会将频繁访问的...

    VLSI-Design of Non-Volatile Memories

    time in the development of technology. Once again, we stand on the brink of a new era where emerging research will yield exciting applications and products destined to transform and enrich our daily ...

    Thinking in Java 习题答案

    《Thinking in Java》是Bruce Eckel的经典编程教材,它深入浅出地介绍了Java语言的核心概念和技术。这本书以其详尽的解释、丰富的示例和实践性强的习题深受程序员喜爱。"Thinking in Java 习题答案"是配套的解答集,...

    【Java面试题】volatile的作用

    【Java面试题】volatile的作用

    violate java-Java 之 volatile 超级详解

    Java中的`volatile`关键字是多线程编程中一个非常重要的概念,它用于修饰变量,确保在并发环境下,多个线程可以正确地共享和同步数据。本文将深入探讨`volatile`关键字的工作原理、特性以及如何使用它来解决多线程中...

    java语言的volatile教程,java语言的volatile关键字是干什么用的

    java语言的volatile教程,java语言的volatile关键字到底怎么用

    Thinking In Java 第四版 【练习题答案 完整版】

    《Thinking in Java》是Bruce Eckel的经典之作,它详尽深入地探讨了Java编程语言的各个方面,被广大程序员视为学习Java的权威指南。第四版在原有的基础上进行了更新,以匹配Java语言的最新发展,包括Java SE 5和6的...

    一文精通Java中的volatile关键字

    Java中的`volatile`关键字是多线程编程中的一个重要概念,它的主要作用是确保共享变量的可见性和禁止指令重排序。本文将深入探讨`volatile`的关键特性、工作原理以及使用注意事项。 1. 可见性: `volatile`关键字...

    thinking in java

    ### 《Thinking in Java》核心知识点解析 #### 一、书籍概述 《Thinking in Java》是一本由布鲁斯·埃克尔(Bruce Eckel)编写的经典Java编程指南。本书首次出版于1998年,并迅速成为学习Java语言的最佳教程之一。...

    Java基础:volatile详解.pdf

    Java基础:volatile详解 Java基础:volatile详解问:谈谈你对volatile的理解? volatile是Java虚拟机提供的轻量级的同步机制,它有三个特性:保证可见性、不保证原子性、禁止指令重排。 1、volatile保证可见性 ...

    The Thinking in Java Annotated Solution Guide

    《Thinking in Java Annotated Solution Guide》是一本针对Bruce Eckel的知名编程教材《Thinking in Java》的注解解答指南。这本书深入浅出地讲解了Java编程语言的核心概念和原理,旨在帮助读者理解并掌握Java编程...

    java里的volatile关键字详解

    "Java中的Volatile关键字详解" Java中的Volatile关键字详解是Java中的一种关键字,用于保证线程之间的可见性、原子性和有序性。下面是对Java中的Volatile关键字详解的知识点总结: 一、基本概念 1. 可见性:可见...

    thinking in java第四版练习题答案

    《Thinking in Java》是Bruce Eckel的经典编程教材,第四版更是深受广大Java程序员喜爱。这本书深入探讨了Java语言的核心概念和编程技术,鼓励读者通过实践思考来理解和掌握Java的精髓。书中包含了大量的练习题,...

    Java并发编程系列- volatile

    Java并发编程中的`volatile`关键字是一个非常重要的概念,它用于解决多线程环境下的数据同步问题。`volatile`关键字提供了两种关键特性: 1. **保证可见性**:当一个线程修改了`volatile`变量,这个修改对于其他...

    java volatile 关键字 学习

    java volatile 关键字 学习

    Thinking in Java知识点总结

    《Thinking in Java》是 Bruce Eckel 的经典著作,其中第21章主要讲解了Java中的并发编程知识。并发编程是让程序在多个线程中同时执行任务,以提高程序的效率和响应性。以下是该章节的重点知识点: 1. **并发的多面...

Global site tag (gtag.js) - Google Analytics