如何在Java中释放内存?

时间:2017-04-19 10:06:58

标签: java memory-management

为了减少GC - 压力,我需要按如下方式分配一定量的堆外内存:

long sz;
//...
long pointer = sun.misc.Unsafe.getUnsafe().allocateMemory(sz);

但由于它不适用于GC,我需要稍后手动解除分配。怎么样?有可能吗?

1 个答案:

答案 0 :(得分:1)

如果你真的读过它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)重新分配。请注意,您始终可以访问openjdk's mercury repository

来访问sun.*课程的来源