3

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?

3
  • It would not be removed immediately, but will be deleted by GC during a subsequent search for de-referenced objects (no guarantee that it'll be picked up at any specific point, even if you "force" garbage collection via System.gc(). Commented Jun 30, 2018 at 3:55
  • So would the thread be interrupted during garbage collection? Commented Jun 30, 2018 at 3:56
  • A non-terminated thread can't be collected and will continue doing its work. Find a place where you exit the thread main loop and use a volatile boolean stop or alike. Alternatively or additionally, use Thread.interrupt (do not swallow the exception). Commented Jul 5, 2018 at 9:43

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.