說說你對Jdk併發包中的CAS實現的瞭解?

    在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);

 JEP 193: Variable Handlesatom

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-alone AtomicInteger (adding both space overhead and additional concurrency issues to manage indirection) or, in some situations, to use atomic FieldUpdaters (often encountering more overhead than the operation itself), or to use the unsafe (and unportable and unsupported) sun.misc.UnsafeAPI 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.

相關文章
相關標籤/搜索