How exactly does Java's garbage collection handle threads?
To clarify, I have a peer to peer network I'm writing in Java, and if a peer is determined to be acting maliciously or is rejected from the routing tables, I remove all references to the Peer object, which extends a thread.
Would I be correct in assuming that even though I deleted all references to the instance, the thread for that instance, and therefore the instance, would not be removed by the garbage collector?
No. It will not be collected or stopped while it is running.
You should stop your thread from within the thread, for example by using using the command return;.
Here is an experiment:
public class Main {
public static void main(String[] args) {
Runnable r = new Runnable(){
public void run() {
for (int i=0; i < 10; i++) {
System.out.println("Thread is running");
}
return;
}
};
Thread t=new Thread(r);
t.start();
t=null;
System.out.println("App finished");
}
}
Here is the result:
App finished
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
So, the thread was not stopped or collected even after the main thread set the reference to null and stopped working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With