3/05/2014

Volatile Variable in Java

The volatile variable in Java is a special variable which is used to signal (flag) in multi-threads programming. By the volatile keyword, the application ensures that its value should always been read from heap memory and other threads should not be used cached value of marked volatile variable from thread's stack.

When to Use Volatile

  • Volatile is most useful for lock-free algorithms. You can mark the variable holding shared fields as volatile when you are not using locking to access that variable and you want changes made by one thread to be visible in another.
  • Volatile is used on variables that may be modified simultaneously by other threads.
  • To save cost of synchronization as volatile variables are less expensive than synchronization.

Volatil Example

Useful Links

  • http://mindprod.com/jgloss/volatile.html
  • http://gee.cs.oswego.edu/dl/jmm/cookbook.html
  • http://malalanayake.wordpress.com/2013/09/12/volatile-vs-static-in-java/
  • http://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

No comments:

Post a Comment