當對象真的被從內存中刪除時,使用弱或軟參考與ReferenceQueue
?我必須撥打referancequeue.remove
或referancequeue.poll()
方法嗎?當對象真的從內存中刪除時,在使用ReferenceQueue時使用弱引用還是軟引用?
例子:
ReferenceQueue q = new ReferenceQueue();
WeakReference wr = new WeakReference(object, referenceQueue);
if (pr.isenqueued()) {
// do something
}
或者我有以下?
WeakReference weakref=null;
if ((weakref=q.removed())!=null) {
// do something
}
你的意思是我必須運行「q.remove()」才能讓java VM自動從內存中移除對象。 – user1764890
當您調用q.remove()時,該對象可以完成並且在完成後可以清理。即可能不會清理一兩個GC。 –