从字面意思就可以看出, 这些接口在java世界, 是不安全的, 都是一些native (jni) 接口, 会直接修改内存中的值, 一旦指针
弄错了, 结果是令人崩溃的.
本文只介绍几个常用的接口.
compareAndSwapInt
原型
/**
* Atomically update Java variable to x if it is currently
* holding expected.
* @return true if successful
*/
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
接口含义:
首先找出Object o
在内存中的位置p
, 然后偏移offset
个字节, 设p+offset
处的这个int值为y
,
如果y == expected
, 则执行赋值操作y = x
, 返回true
如果y != expected
, 则不执行赋值操作, 返回false
使用例子
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeExample {
private final static Logger logger = LogManager.getLogger(UnsafeExample.class);
static Unsafe U;
int x = 2;
static {
Field f = null;
try {
/* 我所使用的jdk8上是theUnsafe */
f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
U = (Unsafe) f.get(null)