Java Unsafe 类

Unsafe类是啥?

Java最初被设计为一种安全的受控环境。尽管如此,Java HotSpot还是包含了一个“后门”,提供了一些可以直接操控内存和线程的低层次操作。这个后门类——sun.misc.Unsafe——被JDK广泛用于自己的包中,如java.nio和java.util.concurrent。但是丝毫不建议在生产环境中使用这个后门。因为这个API十分不安全、不轻便、而且不稳定。这个不安全的类提供了一个观察HotSpot JVM内部结构并且可以对其进行修改。有时它可以被用来在不适用C++调试的情况下学习虚拟机内部结构,有时也可以被拿来做性能监控和开发工具。

为什么叫Unsafe?

Java官方不推荐使用Unsafe类,因为官方认为,这个类别人很难正确使用,非正确使用会给JVM带来致命错误。而且未来Java可能封闭丢弃这个类。

如何使用Unsafe?

1. 获取Unsafe实例:

通读Unsafe源码,Unsafe提供了一个私有的静态实例,并且通过检查classloader是否为null来避免java程序直接使用unsafe:

1//Unsafe源码 2private static final Unsafe theUnsafe; 3@CallerSensitive 4public static Unsafe getUnsafe() { 5 Class var0 = Reflection.getCallerClass(); 6 if(var0.getClassLoader() != null) { 7 throw new SecurityException("Unsafe"); 8 } else { 9 return theUnsafe; 10 } 11}

我们可以通过如下代码反射获取Unsafe静态类:

1/** * 获取Unsafe */ 2Field f = null; 3Unsafe unsafe = null; 4try { 5 f = Unsafe.class.getDeclaredField("theUnsafe"); 6 f.setAccessible(true); 7 unsafe = (Unsafe) f.get(null); 8} catch (NoSuchFieldException e) { 9 e.printStackTrace(); 10} catch (IllegalAccessException e) { 11 e.printStackTrace(); 12}

2. 通过Unsafe分配使用堆外内存:

C++中有malloc,realloc和free方法来操作内存。在Unsafe类中对应为:

1//分配var1字节大小的内存,返回起始地址偏移量 2public native long allocateMemory(long var1); 3//重新给var1起始地址的内存分配长度为var3字节大小的内存,返回新的内存起始地址偏移量 4public native long reallocateMemory(long var1, long var3); 5//释放起始地址为var1的内存 6public native void freeMemory(long var1);

分配内存方法还有重分配内存方法都是分配的堆外内存,返回的是一个long类型的地址偏移量。这个偏移量在你的Java程序中每块内存都是唯一的。
举例:

1/** * 在堆外分配一个byte */ 2long allocatedAddress = unsafe.allocateMemory(1L); 3unsafe.putByte(allocatedAddress, (byte) 100); 4byte shortValue = unsafe.getByte(allocatedAddress); 5System.out.println(new StringBuilder().append("Address:").append(allocatedAddress).append(" Value:").append(shortValue)); 6/** * 重新分配一个long */ 7allocatedAddress = unsafe.reallocateMemory(allocatedAddress, 8L); 8unsafe.putLong(allocatedAddress, 1024L); 9long longValue = unsafe.getLong(allocatedAddress); 10System.out.println(new StringBuilder().append("Address:").append(allocatedAddress).append(" Value:").append(longValue)); 11/** * Free掉,这个数据可能脏掉 */ 12unsafe.freeMemory(allocatedAddress); 13longValue = unsafe.getLong(allocatedAddress); 14System.out.println(new StringBuilder().append("Address:").append(allocatedAddress).append(" Value:").append(longValue));

输出:

1Address:46490464 Value:100 2Address:46490480 Value:1024 3Address:46490480 Value:22

3. 操作类对象

我们可以通过Unsafe类来操作修改某一field。原理是首先获取对象的基址(对象在内存的偏移量起始地址)。之后获取某个filed在这个对象对应的类中的偏移地址,两者相加修改。

1 /** * 获取类的某个对象的某个field偏移地址 */ 2try { 3 f = SampleClass.class.getDeclaredField("i"); 4} catch (NoSuchFieldException e) { 5 e.printStackTrace(); 6} 7long iFiledAddressShift = unsafe.objectFieldOffset(f); 8SampleClass sampleClass = new SampleClass(); 9//获取对象的偏移地址,需要将目标对象设为辅助数组的第一个元素(也是唯一的元素)。由于这是一个复杂类型元素(不是基本数据类型),它的地址存储在数组的第一个元素。然后,获取辅助数组的基本偏移量。数组的基本偏移量是指数组对象的起始地址与数组第一个元素之间的偏移量。 10Object helperArray[] = new Object[1]; 11helperArray[0] = sampleClass; 12long baseOffset = unsafe.arrayBaseOffset(Object[].class); 13long addressOfSampleClass = unsafe.getLong(helperArray, baseOffset); 14int i = unsafe.getInt(addressOfSampleClass + iFiledAddressShift); 15System.out.println(new StringBuilder().append(" Field I Address:").append(addressOfSampleClass).append("+").append(iFiledAddressShift).append(" Value:").append(i));

输出:

Field I Address:3610777760+24 Value:5

4. 线程挂起和恢复

将一个线程进行挂起是通过park方法实现的,调用 park后,线程将一直阻塞直到超时或者中断等条件出现。unpark可以终止一个挂起的线程,使其恢复正常。整个并发框架中对线程的挂起操作被封装在 LockSupport类中,LockSupport类中有各种版本pack方法,但最终都调用了Unsafe.park()方法。

1public class LockSupport { 2 public static void unpark(Thread thread) { 3 if (thread != null) 4 unsafe.unpark(thread); 5 } 6 7 public static void park(Object blocker) { 8 Thread t = Thread.currentThread(); 9 setBlocker(t, blocker); 10 unsafe.park(false, 0L); 11 setBlocker(t, null); 12 } 13 14 public static void parkNanos(Object blocker, long nanos) { 15 if (nanos > 0) { 16 Thread t = Thread.currentThread(); 17 setBlocker(t, blocker); 18 unsafe.park(false, nanos); 19 setBlocker(t, null); 20 } 21 } 22 23 public static void parkUntil(Object blocker, long deadline) { 24 Thread t = Thread.currentThread(); 25 setBlocker(t, blocker); 26 unsafe.park(true, deadline); 27 setBlocker(t, null); 28 } 29 30 public static void park() { 31 unsafe.park(false, 0L); 32 } 33 34 public static void parkNanos(long nanos) { 35 if (nanos > 0) 36 unsafe.park(false, nanos); 37 } 38 39 public static void parkUntil(long deadline) { 40 unsafe.park(true, deadline); 41 } 42}

5. CAS操作

1/** * 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。 * * @param obj 需要更新的对象 * @param offset obj中整型field的偏移量 * @param expect 希望field中存在的值 * @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值 * @return 如果field的值被更改返回true */ 2public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);

6. Clone

如何实现浅克隆?在clone(){…}方法中调用super.clone(),对吗?这里存在的问题是首先你必须继续Cloneable接口,并且在所有你需要做浅克隆的对象中实现clone()方法,对于一个懒懒的程序员来说,这个工作量太大了。
我不推荐上面的做法而是直接使用Unsafe,我们可以仅使用几行代码就实现浅克隆,并且它可以像某些工具类一样用于任意类的克隆。
首先,我们需要一个计算Object大小的工具类:

1class ObjectInfo { 2 /** * Field name */ 3 public final String name; 4 /** * Field type name */ 5 public final String type; 6 /** * Field data formatted as string */ 7 public final String contents; 8 /** * Field offset from the start of parent object */ 9 public final int offset; 10 /** * Memory occupied by this field */ 11 public final int length; 12 /** * Offset of the first cell in the array */ 13 public final int arrayBase; 14 /** * Size of a cell in the array */ 15 public final int arrayElementSize; 16 /** * Memory occupied by underlying array (shallow), if this is array type */ 17 public final int arraySize; 18 /** * This object fields */ 19 public final List<ObjectInfo> children; 20 21 public ObjectInfo(String name, String type, String contents, int offset, int length, int arraySize, 22 int arrayBase, int arrayElementSize) { 23 this.name = name; 24 this.type = type; 25 this.contents = contents; 26 this.offset = offset; 27 this.length = length; 28 this.arraySize = arraySize; 29 this.arrayBase = arrayBase; 30 this.arrayElementSize = arrayElementSize; 31 children = new ArrayList<ObjectInfo>(1); 32 } 33 34 public void addChild(final ObjectInfo info) { 35 if (info != null) 36 children.add(info); 37 } 38 39 /** * Get the full amount of memory occupied by a given object. This value may be slightly less than * an actual value because we don't worry about memory alignment - possible padding after the last object field. * <p/> * The result is equal to the last field offset + last field length + all array sizes + all child objects deep sizes * * @return Deep object size */ 40 public long getDeepSize() { 41 //return length + arraySize + getUnderlyingSize( arraySize != 0 ); 42 return addPaddingSize(arraySize + getUnderlyingSize(arraySize != 0)); 43 } 44 45 long size = 0; 46 47 private long getUnderlyingSize(final boolean isArray) { 48 //long size = 0; 49 for (final ObjectInfo child : children) 50 size += child.arraySize + child.getUnderlyingSize(child.arraySize != 0); 51 if (!isArray && !children.isEmpty()) { 52 int tempSize = children.get(children.size() - 1).offset + children.get(children.size() - 1).length; 53 size += addPaddingSize(tempSize); 54 } 55 56 return size; 57 } 58 59 private static final class OffsetComparator implements Comparator<ObjectInfo> { 60 @Override 61 public int compare(final ObjectInfo o1, final ObjectInfo o2) { 62 return o1.offset - o2.offset; //safe because offsets are small non-negative numbers 63 } 64 } 65 66 //sort all children by their offset 67 public void sort() { 68 Collections.sort(children, new OffsetComparator()); 69 } 70 71 @Override 72 public String toString() { 73 final StringBuilder sb = new StringBuilder(); 74 toStringHelper(sb, 0); 75 return sb.toString(); 76 } 77 78 private void toStringHelper(final StringBuilder sb, final int depth) { 79 depth(sb, depth).append("name=").append(name).append(", type=").append(type) 80 .append(", contents=").append(contents).append(", offset=").append(offset) 81 .append(", length=").append(length); 82 if (arraySize > 0) { 83 sb.append(", arrayBase=").append(arrayBase); 84 sb.append(", arrayElemSize=").append(arrayElementSize); 85 sb.append(", arraySize=").append(arraySize); 86 } 87 for (final ObjectInfo child : children) { 88 sb.append('\n'); 89 child.toStringHelper(sb, depth + 1); 90 } 91 } 92 93 private StringBuilder depth(final StringBuilder sb, final int depth) { 94 for (int i = 0; i < depth; ++i) 95 sb.append("\t"); 96 return sb; 97 } 98 99 private long addPaddingSize(long size) { 100 if (size % 8 != 0) { 101 return (size / 8 + 1) * 8; 102 } 103 return size; 104 } 105 106} 107 108class ClassIntrospector { 109 110 private static final Unsafe unsafe; 111 /** * Size of any Object reference */ 112 private static final int objectRefSize; 113 114 static { 115 try { 116 Field field = Unsafe.class.getDeclaredField("theUnsafe"); 117 field.setAccessible(true); 118 unsafe = (Unsafe) field.get(null); 119 120 objectRefSize = unsafe.arrayIndexScale(Object[].class); 121 } catch (Exception e) { 122 throw new RuntimeException(e); 123 } 124 } 125 126 /** * Sizes of all primitive values */ 127 private static final Map<Class, Integer> primitiveSizes; 128 129 static { 130 primitiveSizes = new HashMap<Class, Integer>(10); 131 primitiveSizes.put(byte.class, 1); 132 primitiveSizes.put(char.class, 2); 133 primitiveSizes.put(int.class, 4); 134 primitiveSizes.put(long.class, 8); 135 primitiveSizes.put(float.class, 4); 136 primitiveSizes.put(double.class, 8); 137 primitiveSizes.put(boolean.class, 1); 138 } 139 140 /** * Get object information for any Java object. Do not pass primitives to * this method because they will boxed and the information you will get will * be related to a boxed version of your value. * * @param obj Object to introspect * @return Object info * @throws IllegalAccessException */ 141 public ObjectInfo introspect(final Object obj) 142 throws IllegalAccessException { 143 try { 144 return introspect(obj, null); 145 } finally { // clean visited cache before returning in order to make 146 // this object reusable 147 m_visited.clear(); 148 } 149 } 150 151 // we need to keep track of already visited objects in order to support 152 // cycles in the object graphs 153 private IdentityHashMap<Object, Boolean> m_visited = new IdentityHashMap<Object, Boolean>( 154 100); 155 156 private ObjectInfo introspect(final Object obj, final Field fld) 157 throws IllegalAccessException { 158 // use Field type only if the field contains null. In this case we will 159 // at least know what's expected to be 160 // stored in this field. Otherwise, if a field has interface type, we 161 // won't see what's really stored in it. 162 // Besides, we should be careful about primitives, because they are 163 // passed as boxed values in this method 164 // (first arg is object) - for them we should still rely on the field 165 // type. 166 boolean isPrimitive = fld != null && fld.getType().isPrimitive(); 167 boolean isRecursive = false; // will be set to true if we have already 168 // seen this object 169 if (!isPrimitive) { 170 if (m_visited.containsKey(obj)) 171 isRecursive = true; 172 m_visited.put(obj, true); 173 } 174 175 final Class type = (fld == null || (obj != null && !isPrimitive)) ? obj 176 .getClass() : fld.getType(); 177 int arraySize = 0; 178 int baseOffset = 0; 179 int indexScale = 0; 180 if (type.isArray() && obj != null) { 181 baseOffset = unsafe.arrayBaseOffset(type); 182 indexScale = unsafe.arrayIndexScale(type); 183 arraySize = baseOffset + indexScale * Array.getLength(obj); 184 } 185 186 final ObjectInfo root; 187 if (fld == null) { 188 root = new ObjectInfo("", type.getCanonicalName(), getContents(obj, 189 type), 0, getShallowSize(type), arraySize, baseOffset, 190 indexScale); 191 } else { 192 final int offset = (int) unsafe.objectFieldOffset(fld); 193 root = new ObjectInfo(fld.getName(), type.getCanonicalName(), 194 getContents(obj, type), offset, getShallowSize(type), 195 arraySize, baseOffset, indexScale); 196 } 197 198 if (!isRecursive && obj != null) { 199 if (isObjectArray(type)) { 200 // introspect object arrays 201 final Object[] ar = (Object[]) obj; 202 for (final Object item : ar) 203 if (item != null) 204 root.addChild(introspect(item, null)); 205 } else { 206 for (final Field field : getAllFields(type)) { 207 if ((field.getModifiers() & Modifier.STATIC) != 0) { 208 continue; 209 } 210 field.setAccessible(true); 211 root.addChild(introspect(field.get(obj), field)); 212 } 213 } 214 } 215 216 root.sort(); // sort by offset 217 return root; 218 } 219 220 // get all fields for this class, including all superclasses fields 221 private static List<Field> getAllFields(final Class type) { 222 if (type.isPrimitive()) 223 return Collections.emptyList(); 224 Class cur = type; 225 final List<Field> res = new ArrayList<Field>(10); 226 while (true) { 227 Collections.addAll(res, cur.getDeclaredFields()); 228 if (cur == Object.class) 229 break; 230 cur = cur.getSuperclass(); 231 } 232 return res; 233 } 234 235 // check if it is an array of objects. I suspect there must be a more 236 // API-friendly way to make this check. 237 private static boolean isObjectArray(final Class type) { 238 if (!type.isArray()) 239 return false; 240 if (type == byte[].class || type == boolean[].class 241 || type == char[].class || type == short[].class 242 || type == int[].class || type == long[].class 243 || type == float[].class || type == double[].class) 244 return false; 245 return true; 246 } 247 248 // advanced toString logic 249 private static String getContents(final Object val, final Class type) { 250 if (val == null) 251 return "null"; 252 if (type.isArray()) { 253 if (type == byte[].class) 254 return Arrays.toString((byte[]) val); 255 else if (type == boolean[].class) 256 return Arrays.toString((boolean[]) val); 257 else if (type == char[].class) 258 return Arrays.toString((char[]) val); 259 else if (type == short[].class) 260 return Arrays.toString((short[]) val); 261 else if (type == int[].class) 262 return Arrays.toString((int[]) val); 263 else if (type == long[].class) 264 return Arrays.toString((long[]) val); 265 else if (type == float[].class) 266 return Arrays.toString((float[]) val); 267 else if (type == double[].class) 268 return Arrays.toString((double[]) val); 269 else 270 return Arrays.toString((Object[]) val); 271 } 272 return val.toString(); 273 } 274 275 // obtain a shallow size of a field of given class (primitive or object 276 // reference size) 277 private static int getShallowSize(final Class type) { 278 if (type.isPrimitive()) { 279 final Integer res = primitiveSizes.get(type); 280 return res != null ? res : 0; 281 } else 282 return objectRefSize; 283 } 284}

我们通过这两个类计算一个Object的大小,通过Unsafe的 public native void copyMemory(Object var1, long var2, Object var4, long var5, long var7)方法来拷贝:
两个工具方法:

1private static Object helperArray[] = new Object[1]; 2/** * 获取对象起始位置偏移量 * @param unsafe * @param object * @return */ 3public static long getObjectAddress(Unsafe unsafe, Object object){ 4 helperArray[0] = object; 5 long baseOffset = unsafe.arrayBaseOffset(Object[].class); 6 return unsafe.getLong(helperArray, baseOffset); 7} 8 9private final static ClassIntrospector ci = new ClassIntrospector(); 10 11/** * 获取Object的大小 * @param object * @return */ 12public static long getObjectSize(Object object){ 13 ObjectInfo res = null; 14 try { 15 res = ci.introspect(object); 16 } catch (IllegalAccessException e) { 17 e.printStackTrace(); 18 } 19 return res.getDeepSize(); 20}

测试:

1SampleClass sampleClass = new SampleClass(); 2sampleClass.setI(999); 3sampleClass.setL(999999999L); 4 5SampleClass sampleClassCopy = new SampleClass(); 6long copyAddress = getObjectAddress(unsafe,sampleClassCopy); 7unsafe.copyMemory(sampleClass, 0, null,copyAddress, getObjectSize(sampleClass)); 8i = unsafe.getInt(copyAddress + iFiledAddressShift); 9System.out.println(i); 10System.out.println(sampleClassCopy.getL());

输出:

1999 2999999999
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )