Java中Unsafe使用详解

开发 后端
在程序中过度、不正确使用Unsafe类会使得程序出错的概率变大,使得Java这种安全的语言变得不再“安全”,因此对Unsafe的使用一定要慎重。

[[392756]]

Unsafe介绍

Unsafe是位于sun.misc包下的一个类,主要提供一些用于执行低级别、不安全操作的方法,如直接访问系统内存资源、自主管理内存资源等,这些方法在提升Java运行效率、增强Java语言底层资源操作能力方面起到了很大的作用。但由于Unsafe类使得Java语言拥有了类似C语言指针一样操作内存空间的能力,这无疑也增加了程序发生相关指针问题的风险。在程序中过度、不正确使用Unsafe类会使得程序出错的概率变大,使得Java这种安全的语言变得不再“安全”,因此对Unsafe的使用一定要慎重。

java.util.concurrent.atomic包下的原子操作类,基本都是使用Unsafe实现的。

Unsafe提供的API大致可分为内存操作、CAS、Class、对象操作、线程、系统信息获取、内存屏障、数组操作等几类。

内存相关

CAS相关

java.util.concurrent.atomic包中的原子类基本都用的Unsafe

  1. private static final Unsafe unsafe = Unsafe.getUnsafe(); 
  2. private static final long valueOffset; 
  3. static { 
  4.   try { 
  5.     valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value")); 
  6.   } catch (Exception ex) { throw new Error(ex); } 
  7. public final int getAndSet(int newValue) { 
  8.   return unsafe.getAndSetInt(this, valueOffset, newValue); 

线程相关

LockSupport类中有应用unpark,park

  1. public static void park(Object blocker) { 
  2.   Thread t = Thread.currentThread(); 
  3.   setBlocker(t, blocker); 
  4.   UNSAFE.park(false, 0L); 
  5.   setBlocker(t, null); 
  1. public static void unpark(Thread thread) { 
  2.   if (thread != null
  3.     UNSAFE.unpark(thread); 

Class相关

对象操作相关

系统相关

内存屏障

loadFence:保证在这个屏障之前的所有读操作都已经完成。

storeFence:保证在这个屏障之前的所有写操作都已经完成。

fullFence:保证在这个屏障之前的所有读写操作都已经完成。

在java8中 有这个StampedLock类,该类中应用了内存屏障功能。

  1. private static final sun.misc.Unsafe U; 
  2. static { 
  3.   try { 
  4.     U = sun.misc.Unsafe.getUnsafe(); 
  5.   } catch (Exception e) { 
  6.     throw new Error(e); 
  7.   } 
  8. public boolean validate(long stamp) { 
  9.   U.loadFence(); 
  10.   return (stamp & SBITS) == (state & SBITS); 

 

  1. U.loadFence(); 

 

Unsafe.java

  1. public final class Unsafe { 
  2.  
  3.     private static native void registerNatives(); 
  4.     static { 
  5.         registerNatives(); 
  6.         sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe"); 
  7.     } 
  8.  
  9.     private Unsafe() {} 
  10.  
  11.     private static final Unsafe theUnsafe = new Unsafe(); 
  12.     // ... 

获取Unsafe实例

Unsafe类是final且是单例的,并且theUnsafe字段是private;通过如下方法获取实例

方法1

  1. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe") ; 
  2. theUnsafe.setAccessible(true) ; 
  3. Unsafe unsafe = (Unsafe) theUnsafe.get(null) ; 

方法2

  1. private static Unsafe unsafe = null ; 
  2.      
  3. static { 
  4.     try { 
  5.         Constructor<Unsafe> cons = Unsafe.class.getDeclaredConstructor() ; 
  6.         cons.setAccessible(true) ; 
  7.         unsafe = cons.newInstance() ; 
  8.     } catch (Exception e) { 
  9.         e.printStackTrace(); 
  10.     } 

Unsafe简单应用

  1. int i = 0 ; 
  2.      
  3. public static void main(String[] args) throws Exception { 
  4.     UnsafeDemo d = new UnsafeDemo() ; 
  5.     // 获取Unsafe实例 
  6.     Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe") ; 
  7.     theUnsafe.setAccessible(true) ; 
  8.     Unsafe unsafe = (Unsafe) theUnsafe.get(null) ; 
  9.     // 获取类的实例变量 
  10.     Field f = UnsafeDemo.class.getDeclaredField("i") ; 
  11.     // 获取字段相对Java对象的"起始地址"的偏移量 
  12.     long fieldOffset = unsafe.objectFieldOffset(f) ; 
  13.     System.out.println(fieldOffset) ; 
  14.     // 设置值 
  15.     boolean success = unsafe.compareAndSwapInt(d, fieldOffset, 0, 10) ; 
  16.     System.out.println(success) ; 
  17.     System.out.println(d.i) ; 

Unsafe对象操作

  1. private static Unsafe unsafe = null ; 
  2.      
  3. static { 
  4. try { 
  5.         Constructor<Unsafe> cons = Unsafe.class.getDeclaredConstructor() ; 
  6.         cons.setAccessible(true) ; 
  7.         unsafe = cons.newInstance() ; 
  8.     } catch (Exception e) { 
  9.         e.printStackTrace(); 
  10.     } 
  11. public static void allocate() { 
  12.     try { 
  13.         Person p = (Person)unsafe.allocateInstance(Person.class) ; 
  14.         p.setId("s001"); 
  15.         System.out.println(p.getValue()) ; 
  16.         System.out.println(p.getId()) ; 
  17.     } catch (Exception e) { 
  18.         e.printStackTrace(); 
  19.     } 

执行结果:

对象操作2:

  1. private Person p = new Person("1""张三") ; 
  2.      
  3. public static void main(String[] args) throws Exception { 
  4.   UnSafeObjectDemo d = new UnSafeObjectDemo() ; 
  5.   Field field = Unsafe.class.getDeclaredField("theUnsafe") ; 
  6.     field.setAccessible(true) ; 
  7.     Unsafe unsafe = (Unsafe) field.get(null) ; 
  8.     Field f = d.getClass().getDeclaredField("p") ; 
  9.     long offset = unsafe.objectFieldOffset(f) ; 
  10.     System.out.println(offset) ; 
  11.     boolean res = unsafe.compareAndSwapObject(d, offset, d.p, new Person("2""李四")) ; 
  12.     System.out.println(res) ; 
  13.     System.out.println(d.p.getName()) ; 

Unsafe创建对象

当不知道即将使用的对象有何构造函数,或是不想使用现有对象的构造函数创建对象时,可以通过如下方式:

  1. Constructor<Teacher> cons = (Constructor<Teacher>) ReflectionFactory.getReflectionFactory().newConstructorForSerialization(Teacher.class, 
  2.                 Object.class.getConstructor()); 
  3. cons.setAccessible(true); 
  4. Teacher t = cons.newInstance() ; 
  5. System.out.println(t) ; 

Unsafe简单实现原子操作类

  1. public class AtomicCount { 
  2.      
  3.     private static Unsafe unsafe ; 
  4.      
  5.     private int value ; 
  6.     private static long valueOffset ; 
  7.      
  8.     static { 
  9.         try { 
  10.             Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe") ; 
  11.             theUnsafe.setAccessible(true) ; 
  12.             unsafe = (Unsafe) theUnsafe.get(null) ; 
  13.              
  14.             Field f = AtomicCount.class.getDeclaredField("value") ; 
  15.             valueOffset = unsafe.objectFieldOffset(f) ; 
  16.         } catch (Exception e) { 
  17.             e.printStackTrace(); 
  18.         } 
  19.     } 
  20.      
  21.     public AtomicCount(int value) { 
  22.         this.value = value ; 
  23.     } 
  24.      
  25.     public final int get() { 
  26.         return value; 
  27.     } 
  28.      
  29.     public final int getAndIncrement() { 
  30.         return unsafe.getAndAddInt(this, valueOffset, 1); 
  31.     } 
  32.      

完毕!!!

 

责任编辑:姜华 来源: 今日头条
相关推荐

2021-04-29 07:43:51

JavaUnsafe 基础native方法

2022-06-07 08:31:44

JavaUnsafe

2016-09-18 16:58:09

JavaProperties

2021-06-03 08:35:25

Go团队Unsafe.Poin

2021-10-12 23:10:58

UnsafeJavaJDK

2015-09-09 08:45:49

JavaThreadLocal

2009-07-20 14:24:13

Math.pow()方Java ME

2011-03-28 09:35:06

iBaitsSqlMapClien

2011-08-15 14:27:51

CocoaRunLoop

2023-10-05 11:12:06

JUCUnsafe安全

2021-10-19 21:39:51

Unsafe构造器内存

2020-12-04 10:11:26

Unsafejava并发包

2011-09-27 10:23:24

Java反射机制

2023-04-23 08:49:17

Java接口Future

2012-02-09 10:18:55

Java

2010-07-22 15:22:58

BlackBerry开

2010-10-09 10:30:03

JS event

2010-09-08 17:15:45

SQL循环结构

2022-03-28 07:15:56

Unsafe框架工具

2019-11-27 10:05:00

LombokJava编程
点赞
收藏

51CTO技术栈公众号