一、前言
关于flink-core源码包中的org.apache.flink.core.memory.MemoryUtils内存工具类,获取sun.misc.Unsafe对象(基于该对象可以调用本地方法allocateMemory、reallocateMemory、freeMemory分别用于分配内存,扩充内存和释放内存)、获取当前内存空间java.nio.ByteOrder二进制存储序列。
二、源码说明
package org.apache.flink.core.memory;@b@@b@import java.lang.reflect.Field;@b@import java.nio.ByteOrder;@b@import sun.misc.Unsafe;@b@@b@public class MemoryUtils@b@{@b@ public static final Unsafe UNSAFE = getUnsafe();@b@ public static final ByteOrder NATIVE_BYTE_ORDER = getByteOrder();@b@@b@ private static Unsafe getUnsafe()@b@ {@b@ Field unsafeField;@b@ try@b@ {@b@ unsafeField = Unsafe.class.getDeclaredField("theUnsafe");@b@ unsafeField.setAccessible(true);@b@ return ((Unsafe)unsafeField.get(null));@b@ } catch (SecurityException e) {@b@ throw new RuntimeException("Could not access the unsafe handle.", e);@b@ } catch (NoSuchFieldException e) {@b@ throw new RuntimeException("The static unsafe handle field was not be found.");@b@ } catch (IllegalArgumentException e) {@b@ throw new RuntimeException("Bug: Illegal argument reflection access for static field.");@b@ } catch (IllegalAccessException e) {@b@ throw new RuntimeException("Access to the unsafe handle is forbidden by the runtime.", e);@b@ }@b@ }@b@@b@ private static ByteOrder getByteOrder()@b@ {@b@ byte[] bytes = new byte[8];@b@ long value = 1311768467284344303L;@b@ UNSAFE.putLong(bytes, UNSAFE.arrayBaseOffset([B.class), 1311768467284344303L);@b@@b@ int lower = bytes[0] & 0xFF;@b@ int higher = bytes[7] & 0xFF;@b@@b@ if ((lower == 18) && (higher == 239))@b@ return ByteOrder.BIG_ENDIAN;@b@ if ((lower == 239) && (higher == 18))@b@ return ByteOrder.LITTLE_ENDIAN;@b@@b@ throw new RuntimeException("Unrecognized byte order.");@b@ }@b@}