Reputation: 1109
Consider the following scenario:
myObj
is instantiated locally in some function myFunc
.myObj
starts a thread someThread
which runs some background task, e.g. reads from a socket.myFunc
then returns, causing myObj
to 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.
Upvotes: 1
Views: 623
Reputation: 54346
An object is only eligible for garbage collection if it has no references to it. You say that someThread
needs to access values stored in myObj
, which means it must have a reference to myObj
. This means that myObj
is not eligible for garbage collection unless someThread
is also eligible.
You can guarantee that an object will never be garbage collected from underneath you so this, for example, is perfectly safe:
void foo() {
final Object something = new String("I'm alive!");
new Thread() {
public void run() {
try {Thread.sleep(10000);} catch (InterruptedException e) {}
System.out.println(something);
}
}.start();
}
something
is 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:
void foo() {
new ThreadStartingObject("I'm alive!");
}
class ThreadStartingObject {
private String message;
public void ThreadStartingObject(String msg) {
this.message = msg;
new Thread() {
public void run() {
try {Thread.sleep(10000);} catch (InterruptedException e) {}
System.out.println(message);
}
}.start();
}
}
The anonymous inner class representing the thread has an implicit reference to the outer this
, i.e. the instance of ThreadStartingObject
. That reference prevents garbage collection.
Upvotes: 3