为了减少GC
压力,我需要分配一些堆外内存,如下所示:
long sz;
//...
long pointer = sun.misc.Unsafe.getUnsafe().allocateMemory(sz);
但由于它不可用于 GC,我需要稍后手动释放它。如何?有可能吗?
如果您真的阅读了它的javadoc,您将无法到达那里:
/** * Allocates a new block of native memory, of the given size in bytes. The * contents of the memory are uninitialized; they will generally be * garbage. The resulting native pointer will never be zero, and will be * aligned for all value types. Dispose of this memory by calling {@link * #freeMemory}, or resize it with {@link #reallocateMemory}. * * @throws IllegalArgumentException if the size is negative or too large * for the native size_t type * * @throws OutOfMemoryError if the allocation is refused by the system * * @see #getByte(long) * @see #putByte(long, byte) */ public native long allocateMemory(long bytes);
所以你需要unsafe.freeMemory(pointer)
解除分配,或者unsafe.reallocateMemory(pointer)
重新分配。请记住,您始终可以sun.*
通过访问openjdk 的 Mercury 存储库来访问类的源代码
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句