输出结果:
静态代码块被执行0
2、通过修改对象中的属性
package com.test.unsafe;import sun.misc.Unsafe;import java.io.*;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.util.HashSet;import java.util.Set;public class UnsafeFooTest {public static void main(String[] args) throws InstantiationException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {Unsafe unsafe = getUnsafe();//通过unsafe修改对象中的属性Guard guard = new Guard();//获取需要修改的属性Field field = guard.getClass().getDeclaredField("ACCESS_ALLOWED");//参数1:修改的对象;参数2:需要修改的属性;参数3:修改的值unsafe.putInt(guard,unsafe.objectFieldOffset(field),88);guard.work();}static class Guard{private int ACCESS_ALLOWED = 1;private void work(){if (ACCESS_ALLOWED == 88){System.out.println("I am working...");}}}//获取Unsafe实例private static Unsafe getUnsafe(){Field field = null;Unsafe unsafe = null;try {field = Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);unsafe = (Unsafe) field.get(null);} catch (Exception e) {e.printStackTrace();}return unsafe;}}
输出结果:
I am working...
3、通过加载类
.java
package com.test.unsafe;import sun.misc.Unsafe;import java.io.*;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.util.HashSet;import java.util.Set;public class UnsafeFooTest {public static void main(String[] args) throws InstantiationException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {Unsafe unsafe = getUnsafe();//通过unsafe加载类 , 他可以跳过JVM校验File file = new File("E:\\classloader1\\com\\test\\unsafe\\MyObject.class");//读取类字节byte[] bytes = loadClassBytes(file);Class> aClass = unsafe.defineClass(null, bytes, 0, bytes.length, UnsafeFooTest.class.getClassLoader(), null);String result = (String) aClass.getMethod("hello").invoke(aClass.newInstance(),null);System.out.println(result);}private static byte[] loadClassBytes(File classFile){try(FileInputStream fls = new FileInputStream(classFile);ByteArrayOutputStream bos = new ByteArrayOutputStream();){byte[] buffer = new byte[1024];int len;while((len=fls.read(buffer))!=-1){bos.write(buffer,0,len);}bos.flush();return bos.toByteArray();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}//获取Unsafe实例private static Unsafe getUnsafe(){Field field = null;Unsafe unsafe = null;try {field = Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);unsafe = (Unsafe) field.get(null);} catch (Exception e) {e.printStackTrace();}return unsafe;}}
.java
package com.test.unsafe;public class MyObject {static {System.out.println("My object static block");}public MyObject(){System.out.println("init");}public String hello(){return "Hello World";}}
输出结果:
My object static blockinitHello World
五、Lock、、、在多线程下的性能比较 1、无任何锁时
package com.test.unsafe;import sun.misc.Unsafe;import java.lang.reflect.Field;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class UnsafeTest {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {//定义线程池ExecutorService executorService = Executors.newFixedThreadPool(1000);Counter counter = new StupidCounter();//记录开始时间long start = System.currentTimeMillis();//提交1000个任务for (int i=0;i
- 能够同时进出车 可直接运行的基于Java多线程的停车场管理系统
- MindMaze要把VR治疗系统带到美国,专攻中风康复治疗
- 2021中国数字智能生态大会,易趋布局项目管理生态合作
- QT窗体绘图QPainter
- BZOJ 1951 浅谈猪王国古代文字及中国剩余定理合并半拓展LuCas
- vagrant使用_使用Vagrant的Kubernetes上的Java EE
- 7 java并发编程实战 并发工具JUC之CountDownLatch
- 中国温度带分布图高清 中国温度带分布高清图
- android 数据库 自动生成,android开发中sqlite代码生成器
- CSS中的 “var” 和 “:root”