Consider the following scenario:
- An object
myObjis instantiated locally in some functionmyFunc. myObjstarts a threadsomeThreadwhich runs some background task, e.g. reads from a socket.myFuncthen returns, causingmyObjto be dereferenced.
Under normal circumstances, the JVM would just garbage-collect myObj. However, if someThread is still running, would this still be the case?
I understand that someThread itself would not be GC’d as long as it is still running, but in my code it also needs to access values stored in myObj, so it is important that I make sure myObj persists while it is still running.
An object is only eligible for garbage collection if it has no references to it. You say that
someThreadneeds to access values stored inmyObj, which means it must have a reference tomyObj. This means thatmyObjis not eligible for garbage collection unlesssomeThreadis also eligible.You can guarantee that an object will never be garbage collected from underneath you so this, for example, is perfectly safe:
somethingis referenced by the anonymous thread so it is not eligible for garbage collection until the anonymous thread is done.More specifically for your example, this is also safe:
The anonymous inner class representing the thread has an implicit reference to the outer
this, i.e. the instance ofThreadStartingObject. That reference prevents garbage collection.