简体   繁体   中英

A new thread object that has not been started will be garbage collected?


I have the source code from a Java Virtual Machine. This VM only garbage collect threads which fullfill these conditions (both conditions):

  • Thread is finished ( started and finished )
  • Thread object does not have any reference

I think it was supposed to garbage collect a not started thread with no refence . But these threads are being held in the VM memory. Is that correct ?


Sample Code:

public class Test implements Runnable{

    private Thread thread;
    public Test() {
        thread = new Thread(this);
    }    

    @Override
    public void run() {
        //This thread never runs...
        //My question is about garbage collector in a situation like this...
    }    
}

Considering:

  • Test object does not have reference anymore
  • The Test object thread never started

The Test thread will be garbage collected ?

An instance of Thread or Runnable class is like an instance of any other class. So, yes it will be GCed if the reference goes out of scope.

Note : You will first have to create an instance of Test .

A running thread acts as root for GC and will not be GCed. Its starting the thread (by calling start() that actually creates a executing thread and makes it special.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM