2017-04-19 35 views
0

爲了減少GC - 壓力我需要分配堆外存儲器的一定量如下:如何在Java中釋放內存?

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

但因爲它是不可用GC,我需要通過手牌後釋放它。怎麼樣?有可能嗎?

+1

不知道更多關於您面臨的實際問題,我只能懷疑使用'sun.misc.Unsafe'是正確的使用方法。 – Axel

+0

@Axel在我們的上下文中,我們沒有找到更好的方法。 –

+2

不安全#allocateMemory上的javadoc有什麼問題? –

回答

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)重新分配。請記住,您總是可以訪問sun.*類的來源openjdk's mercury repository