自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java中Unsafe使用詳解

開發(fā) 后端
在程序中過度、不正確使用Unsafe類會使得程序出錯的概率變大,使得Java這種安全的語言變得不再“安全”,因此對Unsafe的使用一定要慎重。

[[392756]]

Unsafe介紹

Unsafe是位于sun.misc包下的一個類,主要提供一些用于執(zhí)行低級別、不安全操作的方法,如直接訪問系統(tǒng)內(nèi)存資源、自主管理內(nèi)存資源等,這些方法在提升Java運行效率、增強Java語言底層資源操作能力方面起到了很大的作用。但由于Unsafe類使得Java語言擁有了類似C語言指針一樣操作內(nèi)存空間的能力,這無疑也增加了程序發(fā)生相關指針問題的風險。在程序中過度、不正確使用Unsafe類會使得程序出錯的概率變大,使得Java這種安全的語言變得不再“安全”,因此對Unsafe的使用一定要慎重。

java.util.concurrent.atomic包下的原子操作類,基本都是使用Unsafe實現(xiàn)的。

Unsafe提供的API大致可分為內(nèi)存操作、CAS、Class、對象操作、線程、系統(tǒng)信息獲取、內(nèi)存屏障、數(shù)組操作等幾類。

內(nèi)存相關

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相關

對象操作相關

系統(tǒng)相關

內(nèi)存屏障

loadFence:保證在這個屏障之前的所有讀操作都已經(jīng)完成。

storeFence:保證在這個屏障之前的所有寫操作都已經(jīng)完成。

fullFence:保證在這個屏障之前的所有讀寫操作都已經(jīng)完成。

在java8中 有這個StampedLock類,該類中應用了內(nèi)存屏障功能。

  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.     } 

執(zhí)行結果:

對象操作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創(chuàng)建對象

當不知道即將使用的對象有何構造函數(shù),或是不想使用現(xiàn)有對象的構造函數(shù)創(chuàng)建對象時,可以通過如下方式:

  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簡單實現(xiàn)原子操作類

  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.      

完畢!?。?/p>

 

責任編輯:姜華 來源: 今日頭條
相關推薦

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

2024-09-19 20:59:49

2015-09-09 08:45:49

JavaThreadLocal

2011-08-15 14:27:51

CocoaRunLoop

2011-03-28 09:35:06

iBaitsSqlMapClien

2009-07-20 14:24:13

Math.pow()方Java ME

2021-10-19 21:39:51

Unsafe構造器內(nèi)存

2023-10-05 11:12:06

JUCUnsafe安全

2020-12-04 10:11:26

Unsafejava并發(fā)包

2010-07-22 15:22:58

BlackBerry開

2010-10-09 10:30:03

JS event

2010-09-08 17:15:45

SQL循環(huán)結構

2012-02-09 10:18:55

Java

2023-04-23 08:49:17

Java接口Future

2011-09-27 10:23:24

Java反射機制

2025-01-15 07:00:00

Java代碼Lambda
點贊
收藏

51CTO技術棧公眾號