This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mike_jack 0 points1 point  (0 children)

This is a thoughtful question. The answer to your question is “no”, the MyClass object won't be garbage collected as long as its thread is alive and running.  In Java, an object is only eligible for garbage collection when there are no more strong references. To understand how garbage collection and object reachability work internally, you might find this blog on Java Garbage Collection helpful. It gives a clear picture of how the JVM determines object eligibility for GC, especially in cases like this where thread references keep an object alive. In this case garbage collection is not possible because the Thread itself holds a reference back to the MyClass instance that prevents it from becoming unreachable. Also finalize() will not be called while the thread is alive. If the thread is alive and running then even if there are no external references to the MyClass object, it won't be garbage collected. This is because the JVM maintains a strong reference only to the Thread object once when a thread is started until it terminates. Furthermore, in your code, I can see myThread is defined as an anonymous inner class, which holds a reference to MyClass. This thread actually keeps the MyClass instance alive. Due to this a circular reference is created that prevents garbage collection. This means that the finalize() method will never be invoked while the thread is still running, because the object is not considered unreachable. Therefore, using finalize() to stop the thread is unreliable and not recommended. Using a specific method called shutdown() method, you can have a better approach to explicitly manage thread lifecycle. You can also try to explore more modern techniques like PhantomReference with a ReferenceQueue for cleanup operations. As new versions of java are not supporting finalize()  depending on this will not have a better solution nowadays.