在jdk中经过内部提供的Unsafe实现的CAS操做,在这个类的实现中提供了对并发的支持,好比compareAndSwap方法的实现就是原子性的,而且可用来提供高性能、无锁的数据结构。CAS的操做的语义是(compare and set),即比较原值(old)是否和指望(expect)的值相同,若是相同则将该值(old)设置成新值(new)。jdk中的cocurrent包中的atomic、lock、AQS等都是基于该api实现的。java
参考资料:编程
Java并发编程之CASapi
使用Java5+提供的CAS特性而不是使用本身实现的的好处是Java5+中内置的CAS特性能够让你利用底层的你的程序所运行机器的CPU的CAS特性。这会使还有CAS的代码运行更快。数据结构
聊聊并发(二)Java SE1.6中的Synchronized并发
2 术语定义ide
术语 英文 说明 CAS Compare and Swap 比较并设置。用于在硬件层面上提供原子性操做。在 Intel 处理器中,比较并交换经过指令cmpxchg实现。比较是否和给定的数值一致,若是一致则修改,不一致则不修改。
Java Magic. Part 4: sun.misc.Unsafe性能
在使用Unsafe以前,咱们须要建立Unsafe对象的实例。这并不像
Unsafe unsafe = new Unsafe()
这么简单,由于Unsafe的
构造器是私有的。它也有一个静态的getUnsafe()
方法,但若是你直接调用Unsafe.getUnsafe()
,你可能会获得SecurityException异常。只能从受信任的代码中使用这个方法。
this
Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null);
Motivationspa
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.