Unsafe 使用
来源:互联网 发布:平湖市行知小学足球 编辑:程序博客网 时间:2024/06/05 00:53
如果大家看过jdk 源码,那么都应该对Unsafe类有点印象
至于这个类可以用来干什么这里不讨论,主要研究下怎么样使用
这个类常规的方法是不能创建改的
类1:数据封装
public class Data { private int num; public int getNum() { return num; } public void setNum(int num) { this.num = num; }}
类2:工具获取Unsafe
import java.lang.reflect.Field;import java.security.AccessController;import java.security.PrivilegedExceptionAction;import sun.misc.Unsafe;public class Util { private static final Unsafe THE_UNSAFE; static { 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); } }; THE_UNSAFE = AccessController.doPrivileged(action); } catch (Exception e) { throw new RuntimeException("Unable to load unsafe", e); } } public static Unsafe getUnsafe() { return THE_UNSAFE; }}
类3:main
import sun.misc.Unsafe;public class UnsafeTest { public static void main(String[] args) throws NoSuchFieldException, SecurityException { Data data = new Data(); data.setNum(1); Unsafe unsafe = Util.getUnsafe(); long num = unsafe.objectFieldOffset(Data.class.getDeclaredField("num")); unsafe.compareAndSwapInt(data, num, 1, 10); System.out.println(data.getNum()); }}
阅读全文
0 0
- Unsafe 使用
- 关于使用Unsafe code
- unsafe的使用
- Unsafe 基本使用
- unsafe 库使用小结
- unity使用unsafe注意事项
- 使用sun.misc.Unsafe
- Unsafe
- Unsafe
- Unsafe
- C#中unsafe的使用
- C#中unsafe的使用
- C#中unsafe的使用
- unsafe的使用报错
- Unsafe--Java为什么会引入及如何使用Unsafe
- unsafe在C#程序中的使用
- c#指针(unsafe与fixed的使用)
- sun.misc.unsafe类的使用
- leetcode 671. Second Minimum Node In a Binary Tree
- Enum-枚举的正确使用
- Android状态栏微技巧,带你真正理解沉浸式模式
- 静态链接库和动态链接库
- Eclipse Memory Analyzer内存泄漏分析
- Unsafe 使用
- Android开发艺术探索-Activity的启动模式
- struts2 namespace的搜索顺序
- 棋盘覆盖
- 简单数据库操作
- git中的 .gitignore 的忽略规则
- win7 访问其他服务器的docker
- python3 实现 A+B Problem(百练OJ:1000)
- win7桌面文件夹删不掉