Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : What happens if a Runnable that is being used in a thread is set to null?

say I do the following...

//MyRunnable is a class that I have declared, which implements Runnable.

MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

r = null;

What are the implications of setting r to null like I have in the above code snippet ?

like image 683
Heshan Perera Avatar asked Jun 13 '12 09:06

Heshan Perera


2 Answers

Let me explain this to you via figures:

1- At

MyRunnable r = new MyRunnable();

you are creating new instance of class MyRunnable which mostly implements Runnable interface:

enter image description here

2- At

Thread t = new Thread(r);

you are creating a new thread and passing by value the object that the reference r is pointing to:

enter image description here

3- At

r = null;

you are removing the link between the r reference and the MyRunnable object, which Thread t is using to run the thread:

enter image description here

like image 99
Eng.Fouad Avatar answered Oct 19 '22 07:10

Eng.Fouad


No implications.

The Thread has already started. And regardless, the Thread Object will be holding onto the reference so it will not get garbage collected until t does.

like image 6
Jivings Avatar answered Oct 19 '22 08:10

Jivings