Unsafe?
<h4>1、了解Unsafe用法</h4>
翻看java.util.concurrent.atomic下面的源代码。我们知道这些类主要是封装了一些cas原子性操作:
其在java.util.concurrent、java.util.concurrent.locks两个包中被大量使用。我们先找个AtomicInteger类来分析一下:
<pre>
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
<h6>private static final Unsafe unsafe = Unsafe.getUnsafe();</h6>
private static final long valueOffset;
static {
try {
//定位对象的字段在内存中偏移量
valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
public AtomicInteger(int initialValue) {
value = initialValue;
}
public AtomicInteger() {
}
public final int get() {
return value;
}
public final void set(int newValue) {
value = newValue;
}
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
public final int getAndSet(int newValue) {
for (;;) { //循环比较,如果值没有被修改过的话就直接更新,否则循环
int current = get();
if (compareAndSet(current, newValue))
return current;
}
}
<h6>
public final boolean compareAndSet(int expect, int update) { //判断cas操作是否成功
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
</h6>
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int getAndIncrement() { //cas自增,返回原值
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final int getAndDecrement() {//cas自减
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
public final int getAndAdd(int delta) { cas相加,返回原值
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
public final int incrementAndGet() { cas自增,返回新值
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
public final int decrementAndGet() { cas自减返回新值
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
public final int addAndGet(int delta) { cas相加,返回新值
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
public String toString() {
return Integer.toString(get());
}
public int intValue() {
return get();
}
public long longValue() {
return (long)get();
}
public float floatValue() {
return (float)get();
}
public double doubleValue() {
return (double)get();
}
}
</pre>
我们发现里面最核心的方法是:compareAndSwapInt。其实Unsafe只提供了3个核心的cas。
compareAndSwapInt、compareAndSwapLong、compareAndSwapObject 分别对应整数、长整数、对象的cas操作,整理了一下atomic类使用cas操作情况:
当然Unsafe用处这么广,其实它的问题也同样明显:
1、通过循环自旋的方式来做判断,有一些时间消耗
2、常说的ABA问题,即 因为CAS需要在操作值的时候检查下值有没有发生变化,如果没有发生变化则更新,但是如果一个值原来是A,变成了B,又变成了A,那么使用CAS进行检查时会发现它的值没有发生变化,但是实际上却变化过。ABA问题的解决思路就是使用版本号。在变量前面追加上版本号,每次变量更新的时候把版本号加一,那么A-B-A 就会变成1A-2B-3A,在比较值的同时也比较版本号的值。不过也并不是所有的情况都需要这么做,如果我们只是对普通的整形计数的话就算有ABA的情况,也不影响最终的赋值因为在最终的那个节点前我们认为值还是没变的即可原子性的更新值。关于ABA的问题详细可参考:
http://blog.hesey.net/2011/09/resolve-aba-by-atomicstampedreference.html
3、更多的是单个的值的原子性操作, 如需要实现 a + b - c功能,这个时候更多的是通过锁的形式来同步实现
<h4>2、查看sun.misc.Unsafe的源码</h4>
因为Unsafe类包装了很多底层的、非安全的操作。虽然该类及其所有的方法都是public的,但是它只能被受信任的代码使用,并发框架中的很多类,以及Disruptor框架都是使用了Unsafe类。下面我们就在sun.misc包下面找到Unsafe源码看看:
下载jdk 1.7对应的openjdk源码,说明链接:https://jdk7.java.net/source.html 下载链接:openjdk-7u40-fcs-src-b43-26_aug_2013.zip
解压以后在openjdk\jdk\src\share\classes\sun\misc\Unsafe.java就能查看其源码
Unsafe类(因为类太长我只列出部分比较重要)
<b>直接内存操作,如分配、读写、释放内存</b>
<pre>
public native long allocateMemory(long bytes);
public native long reallocateMemory(long address, long bytes);
public native void setMemory(Object o, long offset, long bytes, byte value);
public void setMemory(long address, long bytes, byte value);
public native void copyMemory(Object srcBase, long srcOffset,Object destBase, long destOffset,long bytes);
public void copyMemory(long srcAddress, long destAddress, long bytes);
public native void freeMemory(long address);
public native int addressSize();
public native int pageSize();
</pre>
<b>定位对象的字段在内存中偏移量</b>
<pre>
public native long staticFieldOffset(Field f);
public native long objectFieldOffset(Field f);
public native Object staticFieldBase(Field f);
public native int arrayBaseOffset(Class arrayClass);
public static final int INVALID_FIELD_OFFSET = -1;
public static final int ARRAY_BOOLEAN_BASE_OFFSET = theUnsafe.arrayBaseOffset(boolean[].class);
public static final int ARRAY_BYTE_BASE_OFFSE = theUnsafe.arrayBaseOffset(byte[].class);
public static final int ARRAY_SHORT_BASE_OFFSE = theUnsafe.arrayBaseOffset(short[].class);
public static final int ARRAY_CHAR_BASE_OFFSET = theUnsafe.arrayBaseOffset(char[].class);
public static final int ARRAY_INT_BASE_OFFSET = theUnsafe.arrayBaseOffset(int[].class);
public static final int ARRAY_LONG_BASE_OFFSET= theUnsafe.arrayBaseOffset(long[].class);
public static final int ARRAY_FLOAT_BASE_OFFSET= theUnsafe.arrayBaseOffset(float[].class);
public static final int ARRAY_DOUBLE_BASE_OFFSET= theUnsafe.arrayBaseOffset(double[].class);
public static final int ARRAY_OBJECT_BASE_OFFSET= theUnsafe.arrayBaseOffset(Object[].class);
</pre>
<b>cas操作:</b>
<pre>
public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
public final native boolean compareAndSwapLong(Object o, long offset, long expected, long x);
</pre>
<b>Unsafe的getUnsafe的方法是有授权限制的:</b>
<pre>
@CallerSensitive
public static Unsafe getUnsafe() {
Class cc = Reflection.getCallerClass();
if (cc.getClassLoader() != null)
throw new SecurityException("Unsafe");
return theUnsafe;
}
</pre>
正常情况下去应用Unsafe对象是会异常提示:
<b>不过我们也是有办法可以使我们的代码授信:</b>
1、命令方式: java -Xbootclasspath:/usr/jdk1.7.0/jre/lib/rt.jar:. com.mishadoff.magic.UnsafeClient
2、引用授信代码:
<pre>
public class TestUnsafe {
public static Unsafe getUnsafe() {
Unsafe unsafe = null;
try {
final PrivilegedExceptionAction<Unsafe> action = new PrivilegedExceptionAction<Unsafe>() {
public Unsafe run() throws Exception {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
return (Unsafe) theUnsafe.get(null);
}
};
unsafe = AccessController.doPrivileged(action);
}
catch (Exception e) {
throw new RuntimeException("Unable to load unsafe", e);
}
return unsafe;
}
public static void main(String[] args) {
getUnsafe();
}
}
</pre>
<h4>3、Unsafe c++实现</h4>
1、在openjdk\hotspot\src\share\vm\prims下面找到unsafe.cpp
2、在openjdk\hotspot\src\os_cpu\windows_x86\vm下面找到atomic_windows_x86.inline.hpp
<b>Unsafe.CompareAndSwapInt:</b>
<pre>
UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
UnsafeWrapper("Unsafe_CompareAndSwapInt");
oop p = JNIHandles::resolve(obj);
jint addr = (jint ) index_oop_from_field_offset_long(p, offset); //获取原值的地址
return (jint)(Atomic::cmpxchg(x, addr, e)) == e; //判断原值跟期望的值是否相等
UNSAFE_END
</pre>
<b>cmpxchg:</b>
<pre>
inline jint Atomic::cmpxchg (jint exchange_value, volatile jint dest, jint compare_value) {
// alternative for InterlockedCompareExchange
int mp = os::is_MP();
__asm {
mov edx, dest
mov ecx, exchange_value
mov eax, compare_value
LOCK_IF_MP(mp)
cmpxchg dword ptr [edx], ecx
}
}
</pre>
LOCK_IF_MP:(mp)
<pre>
// Adding a lock prefix to an instruction on MP machine
// VC++ doesn't like the lock prefix to be on a single line
// so we can't insert a label after the lock prefix.
// By emitting a lock prefix, we can define a label after it.
//程序会根据当前处理器的类型来决定是否为cmpxchg指令添加lock前缀。如果程序是在多处理器上运行,就为cmpxchg指令加上lock前缀(lock cmpxchg)。反之,如果程序是在单处理器上运行,就省略lock前缀(单处理器自身会维护单处理器内的顺序一致性,不需要lock前缀提供的内存屏障效果)。
define LOCK_IF_MP(mp) __asm cmp mp, 0 \
__asm je L0 \
__asm _emit 0xF0 \
__asm L0:
</pre>
所以Unsafe采用的是cpu级别的lock比synchronized的性能更加