开发者

Java Garbage Collector clarification

Right now I'm reading this article regarding Java Garbage Collection: http://www.javaworld.com/javaworld/jw-08-1996/jw-08-gc.html?

Here is a snippet of a function in a JMS client

public void foo(){
    ...//Create Co开发者_如何学JAVAnnection factory, connection, and session, topic

    TopicSubscriber tp = session.createDurableSubcriber(topic,"001");
    tp.setMessageListener(this)
}

This question isn't about JMS but more what happens with the object "tp" after foo() function call has ended. After the function ends there is no way to reference tp anymore. I'm assuming in createDurableSubscriber() that it's using the keyword "new" which means that the object is being placed on the JVM heap. However since tp can no longer be referenced is it subject to the JVM garbage collection?


You need to look in the source code for session.createDurableSubcriber() to see if it doesn't store the value it will return to you somewhere.

Remember you are basically getting a pointer (called reference in Java) to the object, not the object itself, and that pointer can be stored numerous places even if you only have a single object. All these pointer references must be done with before the object can be reclaimed by the garbage collector.


Possibly. It might still be referenced through some chain of pointers starting at a static variable somewhere.


It could be referenced in your session as a field or passed anywhere else depending on the JMS implementation. JMS is only an API, you simply can't suppose anything about the implementation, and you can't suppose that tp isn't referenced anymore.

But to answer the question, if you "suppose" anyway that it isn't referenced, yes the GC would take care of it.


An object will only be collected if no running code has a reference to it (excluding weak references, which few people generally mess with anyway -- weak references don't count for determining collectibility.).

In your example, if you assume that create... actually creates a new object, and doesn't store a reference to it for some reason, and that attaching a listener to said object doesn't require creating a link back to the observable, then yes -- tp will probably be eligible for finalization and collection.

If any of those assumptions are wrong, though, all bets are off.


It is important to distinguish between objects and variables (which holds references to objects). An object becomes eligible for garbage collection when there are no more references to it.

In you particular case, createDurableSubscriber will have kept a copy of the reference it returned, thereby preventing the object from being collected. (After all, it needs to invoke methods on that object when a new message arrives, which is hard to do without a reference),

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜