目录
一、Unsafe介绍
二、获取Unsafe类
三、Unsafe功能介绍
1、内存的分配和释放
2、park和Unpark
3、跨方法锁
4、cas
unsafe提供了一系列native方法。具体功能有cas、内存申请与释放、park和unpark、内存屏障、跨方法锁(jdk11不再提供该方法)。
我们一般有以下的几种方法去使用一个类,但是在这里我们只能使用反射来获取使用。
package tools.unsafe;import sun.misc.Unsafe;import flect.Field;/*** @Auther: duanYL* @Date: 2023/10/26/10:54* @Description:*/
public class GetUnsafe {public static void main(String[] args) {Unsafe unsafe = getUnsafeInstance();System.out.println(unsafe);}public static Unsafe getUnsafeInstance() {try {Field field = DeclaredField("theUnsafe");field.setAccessible(true);return (Unsafe) (null);} catch (Exception e) {e.printStackTrace();}return null;}
}
分配的是系统内存,不被JVM管理,所以还要手动释放
package tools.unsafe;import sun.misc.Unsafe;public class AllocateMemoryAccess {public static void main(String[] args) {Unsafe unsafe = UnsafeInstance();long temp = 123456789L;byte size = 8;/** 调用allocateMemory分配内存*/long memoryAddress = unsafe.allocateMemory(size);System.out.println("分配的地址 :-> "+memoryAddress);/** 写入到内存中*/unsafe.putAddress(memoryAddress, temp);/** 内存中读取数据*/long readValue = Address(memoryAddress);System.out.println("从指定地址取得的value : " + readValue);unsafe.freeMemory(memoryAddress);}@Overrideprotected void finalize() throws Throwable {super.finalize();}
}
package tools.unsafe;import sun.misc.Unsafe;import urrent.TimeUnit;/*** @Auther: duanYL* @Date: 2023/10/26/13:56* @Description:*/
public class TestParkAndUnPark {public static void main(String[] args) {Unsafe unsafe = UnsafeInstance();Thread thread = new Thread(() -> {//如果第一个参数为true,则会实现定时System.out.println("thread park !");unsafe.park(false,0);System.out.println("thread unpark !");});thread.start();try {TimeUnit.SECONDS.sleep(4);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("唤醒线程!!");unsafe.unpark(thread);}
}
synchronized锁住的是一个方法的一块区域,但是unsafe提供的锁,可以在不同的方法里面加锁释放。这个方法在jdk11就不再提供了。
unsafepareAndSwapInt(this, valueOffTemp, old, target)保证了同一时间只有一个线程能改变该值。其中valueOffTemp是在TestCAS类中,temp变量所在的内存位置。
package tools.unsafe;import sun.misc.Unsafe;/*** @Auther: duanYL* @Date: 2023/10/26/14:09* @Description:*/
public class TestCAS {static final Unsafe unsafe = UnsafeInstance();private volatile int temp;private static final long valueOffTemp;public TestCAS(int temp){p=temp;}public int getTemp(){p;}public static void main(String[] args) throws NoSuchFieldException {TestCAS testCAS = new TestCAS(0);System.out.println("改变前的值:" + Temp());testCASpareAndSwapInt(0,1);System.out.println("改变后的值:" + Temp());}static {try {valueOffTemp = unsafe.objectFieldOffset(DeclaredField("temp"));System.out.println("valueOffset:--->"+valueOffTemp);} catch (NoSuchFieldException e) {throw new RuntimeException(e);}}public boolean compareAndSwapInt(int old,int target){return unsafepareAndSwapInt(this, valueOffTemp, old, target);}
}
本文发布于:2024-02-03 07:36:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170691696949576.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |