gpt4 book ai didi

java - Java中如何释放内存?

转载 作者:行者123 更新时间:2023-12-02 13:23:01 26 4
gpt4 key购买 nike

为了减少 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) 来重新分配。请记住,您始终可以通过访问 openjdk's mercury repository 来访问 sun.* 类的源代码。

关于java - Java中如何释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com