Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen when a Java thread is set to null?

After a thread started, if the reference of the thread is set to null, what will happen to the thread? Does it stop? Is it eligible for GC?

Like this:

t.start(); t = null; 
like image 769
alan Avatar asked Jul 13 '11 08:07

alan


People also ask

What is null thread in Java?

The java. lang. NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What happens when a thread dies in Java?

Dead. A thread can die in two ways: either from natural causes, or by being killed (stopped). A thread dies naturally when its run() method exits normally. For example, the while loop in this method is a finite loop--it will iterate 100 times and then exit.

How threads are executed in Java?

start. Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

What are the threads in Java?

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.


2 Answers

Live thread will continue running even its reference is set to null.
Just like any other object, when there are no references to it, it is eligible to GC. The tricky point is that a running thread has a reference in a ThreadGroup even if your program does not retain one, thus a running thread is never GCed.

like image 90
Saurabh Gokhale Avatar answered Sep 18 '22 13:09

Saurabh Gokhale


what will happen to the thread?

Nothing.

Does it stop?

No.

Is it eligible for GC?

No.

like image 44
user207421 Avatar answered Sep 18 '22 13:09

user207421