如何在Java中释放内存?
为了减少GC的压力,我需要分配一些堆外内存,如下所示:如何在Java中释放内存?,java,memory-management,Java,Memory Management,为了减少GC的压力,我需要分配一些堆外内存,如下所示: long sz; //... long pointer = sun.misc.Unsafe.getUnsafe().allocateMemory(sz); 但由于GC无法使用它,我需要稍后手动解除分配它。怎么用?有可能吗?如果你真的读了它,你就到不了那里: 因此,您需要unsafe.freemory(指针)来解除分配,或者unsafe.reallocatemory(指针)来重新分配。请记住,通过访问,您始终可以访问sun.*类的源代码,而
long sz;
//...
long pointer = sun.misc.Unsafe.getUnsafe().allocateMemory(sz);
但由于GC无法使用它,我需要稍后手动解除分配它。怎么用?有可能吗?如果你真的读了它,你就到不了那里:
因此,您需要
unsafe.freemory(指针)
来解除分配,或者unsafe.reallocatemory(指针)
来重新分配。请记住,通过访问,您始终可以访问sun.*
类的源代码,而不必了解您所面临的实际问题,我只能怀疑使用sun.misc.Unsafe
是否正确。@Axel在我们的上下文中,我们没有找到更好的方法。不安全的#allocateMemory上的javadoc有什么问题吗?看看吧。在这里,您将了解如何使用freeMemory()。因为您的代码类似于sun.misc.Unsafe.getUnsafe().freemory(指针);
/**
* 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);