1.Unsafe
java concurrent 包的基礎(chǔ)是CAS, 而進(jìn)行CAS操作的就是這個(gè) Unsafe類.
廢話不說了, 直接上代碼:
Unsafe 類是Java中的保護(hù)類, 在外面包中使用通常通過反射獲取 Unsafe類實(shí)例
/**
*
* Unsafe 類是java中的保護(hù)類, 所以就通過這種方式獲取(ps 也可以在命令行中指定所加載的包是受保護(hù)的)
* Created by xjk on 2016/5/13.
*/
public class UnSafeClass {
private static Unsafe unsafe;
static{
try {
// 通過反射的方式獲取unsafe類
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static Unsafe getInstance(){
return unsafe;
}
}
再來一段Unsafe類在 concurrent 包中的使用
import com.lami.tuomatuo.search.base.concurrent.unsafe.UnSafeClass;
import sun.misc.Unsafe;
/**
* Created by xjk on 1/13/17.
*/
public class Node<E> {
volatile E item;
volatile Node<E> next;
Node(E item){
/**
* Stores a reference value into a given Java variable.
* <p>
* Unless the reference <code>x</code> being stored is either null
* or matches the field type, the results are undefined.
* If the reference <code>o</code> is non-null, car marks or
* other store barriers for that object (if the VM requires them)
* are updated.
* @see #putInt(Object, int, int)
*
* 將 Node 對(duì)象的指定 itemOffset 偏移量設(shè)置 一個(gè)引用值
*/
unsafe.putObject(this, itemOffset, item);
}
boolean casItem(E cmp, E val){
/**
* Atomically update Java variable to <tt>x</tt> if it is currently
* holding <tt>expected</tt>.
* @return <tt>true</tt> if successful
* 原子性的更新 item 值
*/
return unsafe.compareAndSwapObject(this, itemOffset, cmp, val);
}
void lazySetNext(Node<E> val){
/**
* Version of {@link #putObjectVolatile(Object, long, Object)}
* that does not guarantee immediate visibility of the store to
* other threads. This method is generally only useful if the
* underlying field is a Java volatile (or if an array cell, one
* that is otherwise only accessed using volatile accesses).
*
* 調(diào)用這個(gè)方法和putObject差不多, 只是這個(gè)方法設(shè)置后對(duì)應(yīng)的值的可見性不一定得到保證,
* 這個(gè)方法能起這個(gè)作用, 通常是作用在 volatile field上, 也就是說, 下面中的參數(shù) val 是被volatile修飾
*/
unsafe.putOrderedObject(this, nextOffset, val);
}
/**
* Atomically update Java variable to <tt>x</tt> if it is currently
* holding <tt>expected</tt>.
* @return <tt>true</tt> if successful
*
* 原子性的更新 nextOffset 上的值
*
*/
boolean casNext(Node<E> cmp, Node<E> val){
return unsafe.compareAndSwapObject(this, nextOffset, cmp, val);
}
private static Unsafe unsafe;
private static long itemOffset;
private static long nextOffset;
static {
try {
unsafe = UnSafeClass.getInstance();
Class<?> k = Node.class;
itemOffset = unsafe.objectFieldOffset(k.getDeclaredField("item"));
nextOffset = unsafe.objectFieldOffset(k.getDeclaredField("next"));
}catch (Exception e){
}
}
}
上面的代碼是一個(gè)鏈表節(jié)點(diǎn)的代碼, 主要方法:
1. unsafe.putObject(this, itemOffset, item)
直接在對(duì)象的itemOffset位置設(shè)置item的引用
2. unsafe.compareAndSwapObject(this, itemOffset, cmp, val)
通過比較itemOffset上是否為引用cmp的值, 來設(shè)置val
3. unsafe.putOrderedObject(this, nextOffset, val)
在對(duì)象的itemOffset位置設(shè)置item的引用, 只不過這個(gè)方法的可見性比直接用 putObject 方法低一點(diǎn), 其他的線程要過一段時(shí)間才可見
這三個(gè)方法中 putObject, compareAndSwapObject 是常用方法, putOrderedObject相對(duì)來說就神秘一下, 就下來我們就聊這個(gè)方法
putOrderedObject: 將這個(gè)方法名拆成 put ordered Object, 這下就好理解一點(diǎn), 按照order來進(jìn)行寫; 在底層操作時(shí)使用 store-store barrier(), 不會(huì)被Java的JIT重新排序; 它通常用于元素 nulling out fileds (即刪除), 在AtomicXX 中通常用于 LazySet;
As probably the last little JSR166 follow-up for Mustang, we added a "lazySet" method to the Atomic classes (AtomicInteger, AtomicReference, etc). This is a niche method that is sometimes useful when fine-tuning code using non-blocking data structures. The semantics are that the write is guaranteed not to be re-ordered with any previous write, but may be reordered with subsequent operations (or equivalently, might not be visible to other threads) until some other volatile write or synchronizing action occurs).
The main use case is for nulling out fields of nodes in non-blocking data structures solely for the sake of avoiding long-term garbage retention; it applies when it is harmless if other threads see non-null values for a while, but you'd like to ensure that structures are eventually GCable. In such cases, you can get better performance by avoiding the costs of the null volatile-write. There are a few other use cases along these lines for non-reference-based atomics as well, so the method is supported across all of the AtomicX classes.
For people who like to think of these operations in terms of machine-level barriers on common multiprocessors, lazySet provides a preceeding store-store barrier (which is either a no-op or very cheap on current platforms), but no store-load barrier (which is usually the expensive part of a volatile-write).
這三句話是 Doug Lea 寫的 鏈接, 調(diào)用這個(gè)方法產(chǎn)生的效果是: write操作不會(huì)和前面的寫操作重排序, 但是可能會(huì)被隨后的操作重排序(即隨后的操作中可能不可見), 直到其他的volatile寫或同步事件發(fā)生;
主要用于無阻塞數(shù)據(jù)結(jié)構(gòu)的 nulling out, 就像上面的 lazySet 方法, 它是在 ConcurrentLinkedQueue中刪除節(jié)點(diǎn)中使用的, 比如下面的刪除原隊(duì)列頭節(jié)點(diǎn):
/**
* Tries to CAS head to p, If successfully, repoint old head to itself
* as sentinel for succ(), blew
*
* 將節(jié)點(diǎn) p設(shè)置為新的節(jié)點(diǎn)(這是原子操作),
* 之后將原節(jié)點(diǎn)的next指向自己, 直接變成一個(gè)哨兵節(jié)點(diǎn)(為queue節(jié)點(diǎn)刪除及garbage做準(zhǔn)備)
*
* @param h
* @param p
*/
final void updateHead(Node<E> h, Node<E> p){
if(h != p && casHead(h, p)){
h.lazySetNext(h);
}
}
刪除節(jié)點(diǎn)后 調(diào)用 lazySetNext(其實(shí)是 putOrderedObject) 來將自己的next指向自己
ps: 這里為啥不調(diào)用 putObject呢, 原因非常簡(jiǎn)單, putOrderedObject 使用 store-store barrier屏障, 而 putObject還會(huì)使用 store-load barrier 屏障(對(duì)于Java中的指令屏障不了解的直接可以參考 Java并發(fā)編程藝術(shù))
2. unsafe總結(jié):
unsafe類是溝通java代碼和計(jì)算機(jī)底層的一把神奇的鑰匙 , 而在實(shí)際的通常用于原子性的改變對(duì)象中的某個(gè)變量
3. LockSupport
LockSupport 的主要功能是提供線程一個(gè)"許可", 通過這個(gè)"許可"來控制線程的阻塞和恢復(fù); 它主要有下面這幾個(gè)方法
/**
* 阻塞當(dāng)前線程, 直到調(diào)用 LockSupport.unpark(Thread), 或進(jìn)行線程中斷
* 若線程是通過中斷的方式進(jìn)行喚醒, 則 不會(huì)拋出異常, 且中斷標(biāo)示不會(huì)更改, 需要調(diào)用
* Thread.interrupted() 才能清除
*/
1. LockSupport.park();
/** 和上面的差不多, 只是加個(gè)object(在jstack時(shí),有了這個(gè)對(duì)象方便定位問題)
* ps: 不是對(duì)這個(gè)對(duì)象阻塞, 只是當(dāng)前線程阻塞, 這個(gè)object只是定位問題的參數(shù)
*/
2. LockSupport.park(Object object);
/** 和上面的差不多, 只是加個(gè)timeout
*/
3. LockSupport.park(lont timeout);
/** 和上面的差不多, 只是加個(gè)deadline(絕對(duì)時(shí)間, 就是未來某刻的時(shí)間戳)
*/
4. LockSupport.parkUntil(lont deadline);
/** 喚醒線程
*/
5. LockSupport.unpark(Thread);
LockSupport和Unsafe都是 java并發(fā)編程的基礎(chǔ)類, 它們的api都比簡(jiǎn)單, 寫幾個(gè)小demo就可以了
參考資料:
lazySet
bugs.java
unsafe.cpp