在jdk中通过内部提供的Unsafe实现的CAS操作,在这个类的实现中提供了对并发的支持,比如compareAndSwap方法的实现就是原子性的,并且可用来提供高性能、无锁的数据结构。CAS的操作的语义是(compare and set),即比较原值(old)是否和期望(expect)的值相同,如果相同则将该值(old)设置成新值(new)。jdk中的cocurrent包中的atomic、lock、AQS等都是基于该api实现的。
参考资料:
使用Java5+提供的CAS特性而不是使用自己实现的的好处是Java5+中内置的CAS特性可以让你利用底层的你的程序所运行机器的CPU的CAS特性。这会使还有CAS的代码运行更快。
聊聊并发(二)Java SE1.6中的Synchronized
2 术语定义
术语 英文 说明 CAS Compare and Swap 比较并设置。用于在硬件层面上提供原子性操作。在 Intel 处理器中,比较并交换通过指令cmpxchg实现。比较是否和给定的数值一致,如果一致则修改,不一致则不修改。
Java Magic. Part 4: sun.misc.Unsafe
在使用Unsafe之前,我们需要创建Unsafe对象的实例。这并不像
Unsafe unsafe = new Unsafe()
这么简单,因为Unsafe的
构造器是私有的。它也有一个静态的getUnsafe()
方法,但如果你直接调用Unsafe.getUnsafe()
,你可能会得到SecurityException异常。只能从受信任的代码中使用这个方法。
Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null);
Motivation
As concurrent and parallel programming in Java continue to expand, programmers are increasingly frustrated by not being able to use Java constructs to arrange atomic or ordered operations on the fields of individual classes; for example, atomically incrementing a
count
field. Until now the only ways to achieve these effects were to use a stand-aloneAtomicInteger
(adding both space overhead and additional concurrency issues to manage indirection) or, in some situations, to use atomicFieldUpdater
s (often encountering more overhead than the operation itself), or to use the unsafe (and unportable and unsupported)sun.misc.Unsafe
API for JVM intrinsics. Intrinsics are faster, so they have become widely used, to the detriment of safety and portability.Without this JEP, these problems are expected to become worse as atomic APIs expand to cover additional access-consistency policies (aligned with the recent C++11 memory model) as part of Java Memory Model revisions.