Does a PhantomReference being in a ReferenceQueue stop the PhantomReference from being GC'd?

后端 未结 2 2064
半阙折子戏
半阙折子戏 2021-02-20 07:39

I\'m using the LWJGL libraries and unfortunately I need to free up texture/vbo buffers myself whenever a node in my scene graph needs to die, I can\'t even use finalize() method

相关标签:
2条回答
  • 2021-02-20 08:04

    PhantomReference object is added to the queue when the referenced object id GC'd, not the PhantomReference itself. If you don't add a PhantomReference to a List, there is no reference to PhantomReference object, and thus it is GC'd immediately and never makes into the queue.

    0 讨论(0)
  • 2021-02-20 08:17

    Disclaimer: I have not ever used PhantomReference.

    However, I did read this article and this javadoc page, and so

    1. "Is adding it to a list like this needed? [...] (maybe the Game.phantomReferenceQueue keeps a reference to it?)": As per the javadoc page: "Reference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected.". So I believe that no, you shouldn't add it the List, since the Queue will automatically have it added by the garbage collector.
    2. I think you have to rephrase a little bit your question - I don't understand what the List is for, i.e. I don't understand the last paragraph. But if you're using the list in order to know if the phantomReference is gc'ed then no, you should not be using the list at all, that's what the ReferenceQueue is there for. Moreover, the List will prevent the phantomReference from being gc'ed!

    Edit: Read the title of your post again. To answer the title question by itself: No, because a PhantomReference enters the ReferenceQueue after it has been gc'ed - so by definition it cannot be stopped from being gc'ed. To quote the first link: "The only use for such a reference [note: he means PhantomReference] is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead"

    Edit #2: I also think your code is wrong in that you should be initialising the phantom reference as follows (see a simple example here):

    PhantomReference scenePhantomRef = new PhantomReference(scene, phantomQueue);
    

    where scene is the ScenePhantomReference from your code (i.e. you should refactor your code so that ScenePhantomReference is name e.g. Scene, you instantiate it as scene and then use the line above to get a handle on a PhantomReference for that object).

    0 讨论(0)
提交回复
热议问题