What is volatile variable in Java - When to use

volatile  variable in Java is a special variable which is used to signal threads, compiler that this particular variables values is going to be updated by  multiple  thread inside Java application. By making a variable volatile using  volatile keyword in Java, application programmer ensures that its value should always been read from  main memory  and thread should not used cached value of that variable from there own stack. With the introduction of Java memory model from Java 5 onwards along with introduction of  CountDownLatch CyclicBarrier Semaphore  and  ConcurrentHashMap , volatile variable also guarantees  "happens-before"  relationship, which means not only other thread has visibility of latest value of volatile variable but also all the variable seen by the thread which has updated value of volatile variable before this threads sees it. What is volatile variable and when to use it is always a  popular Java threading question .



Important point related to volatile keyword in Java
Since volatile keyword is used to make any variable volatile in Java environment, its good to know more about  What is volatile keyword , what is its limitation and How to use volatile keyword in Java.
What is volatile variable in Java and when to use it
1) Volatile keyword can only be applied to variable, it can not be applied to class or method. using volatile keyword along with class and method is compiler error.

2) volatile is also refereed as modifier in Java.


When to use Volatile variable in Java
This is the most important thing to learn while learning about  volatile variable in Java . When to use volatile variable in Java is also a famous multi-threading interview question in Java. here are some of the scenario where you can use volatile variable in Java :

1) Any variable which is shared between  multiple  threads should be made variable, in order to ensure that all thread must see latest value of volatile variable.

2) A signal to compiler and JIT to ensure that compiler does not  change  ordering or volatile variable and moves them out of synchronized context.

3) You want to save cost of synchronization as volatile variables are  less expensive  than synchronization.

That's all on What is volatile variable in Java, When to use volatile variable in Java. volatile variable is an important concept to understand and use. Its also very important in terms of  Java interview point of view.



Other  tutorial on Java  from this blog
Top thread interview question for Java programmer - Beginners
Top Java coding interview question for Senior Java programmer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值