The volatile keyword in Java 5

We've so far seen that a volatile variable is essentially one whose value is always held in main memory so that it can be accessed by different threads. Java 5 adds a subtle change to this definition and adds some additional facilities for manipulating volatile variables.

Java 5 definition of volatile

As of Java 5, accessing a volatile variable creates a memory barrier: it effectively synchronizes all cached copies of variables with main memory, just as entering or exiting a synchronized block that synchronizes on a given object. Generally, this doesn't have a big impact on the programmer, although it does occasionally make volatile a good option for safe object publication. The infamous double-checked locking antipattern actually becomes valid in Java 5 if the reference is declared volatile. (See the page on how to fix double-checked locking for an example.) Andvolatiles memory synchronization behaviour has occasionally allowed more efficient design in some of the library classes via a technique dubbed synchronization 'piggybacking'.


New Java 5 functionality for volatile variables

Perhaps more significant for most programmers is that as of Java 5, the VM exposes some additional functionality for accessing volatile variables:

  • truly atomic get-and-set operations are permitted;
  • an efficient means of accessing the nth element of a volatile array (and performing atomic get-and-set on the element) is provided.

These facilities are tucked away inside the sun.misc.Unsafe class1, but exposed to the programmer in the form of various new concurrency classes:

Next...

On the following pages, we look at:


1. This is clearly a detail of Sun's implementation; other JVMs could in principle implement the atomic classes without having a separate layer such assun.misc.Unsafe.

Article written by Neil Coffey (@BitterCoffey).

Reference: http://www.javamex.com/tutorials/synchronization_volatile_java_5.shtml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值