Unsafe 的简单使用
生活随笔
收集整理的這篇文章主要介紹了
Unsafe 的简单使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Unsafe 簡介
Unsafe 是sun.misc包中的一個類,可以通過內存偏移量操作類變量/成員變量
Unsafe 用途
AQS(AbstractQueuedSynchronizer) 常用作實現輕量級鎖,它里面有一個雙向鏈表,用于封裝未搶到鎖的線程 ,其中有用到
Unsafe的compareAndSwapObject修改鏈表
Unsafe 簡單使用示例
package com.xh.kssfwjg.idgenerator;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
* TODO
*
* @auther xh
* @date 12/26/18 6:11 PM
*/
public class UnSaveTest {
private static final Unsafe unsafe = getUnsafe();
private static final long objectNameOffset;
private static final long staticNameOffset;
private static String staticName = "qq";
private String objectName = "123";
static {
try {
objectNameOffset = unsafe.objectFieldOffset
(UnSaveTest.class.getDeclaredField("objectName"));
staticNameOffset = unsafe.staticFieldOffset(UnSaveTest.class.getDeclaredField("staticName"));
} catch (NoSuchFieldException e) {
throw new Error(e);
}
}
public static void main(String[] args) {
UnSaveTest unSaveTest = new UnSaveTest();
// unsafe.compareAndSwapObject(unSaveTest, testOffset, "123", "456");//CAS
unsafe.putObject(unSaveTest, objectNameOffset, "haha");//直接修改
unsafe.putObject(UnSaveTest.class, staticNameOffset, "hehe");//直接修改
System.out.println(unSaveTest.objectName);
System.out.println(UnSaveTest.staticName);
}
private static Unsafe getUnsafe() {
Field singleoneInstanceField = null;
try {
singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
singleoneInstanceField.setAccessible(true);
return (Unsafe) singleoneInstanceField.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
output:
haha
hehe
ps:
如果變量使用
final修飾,如:
private static final String staticName = "qq";
private final String objectName = "123";
是不能修改的.
另外附上反射的示例
try {
Class clazz = Class.forName("com.xh.kssfwjg.idgenerator.UnSaveTest");
Object o = clazz.newInstance();
Field object_field_name = clazz.getDeclaredField("objectName");
object_field_name.setAccessible(true);
object_field_name.set(o, "ooo");
Field static_field_name = clazz.getDeclaredField("staticName");
static_field_name.setAccessible(true);
static_field_name.set(clazz, "ppp");
System.out.println(UnSaveTest.staticName);
System.out.println(((UnSaveTest) o).objectName);
} catch (Exception e) {
e.printStackTrace();
}
結果一樣
總結
以上是生活随笔為你收集整理的Unsafe 的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 拼多多_拼多多现重大BUG
- 下一篇: OAuth2.0(基于django2.1