Reputation: 31020
update: looks like it's not a memory leak, would someone create on based on an extension of this example?
Original question:
Suppose I create and starts a thread that does not terminate, the thread creates an object and references as long as it's alive. See the following code. Would the JVM garbage collect x
?
would this be considered a memory leak?
public class MyRunnable implements Runnable{
public void run(){
X x = new X();
while(true){}
}
}
Thread t = new Thread(new MyRunnable());
t.start();
Upvotes: 7
Views: 331
Reputation: 15886
From Wiki
A memory leak may happen when an object is stored in memory but cannot be accessed by the running code. So
would this be considered a memory leak?
NO this is not a memory leak.
Would jvm garbage collect x ?
NO because thread will never end.
Upvotes: 0
Reputation: 13872
Would jvm garbage collect x?
Nope, Cause thread is still maintains refrence to it.
would this be considered a memory leak?
Not really a leak, but wastage of memory.
Upvotes: 0
Reputation: 41945
x
has method scope and will not be garbage collected until method returns or you explicitly do x = null
.
And no this will not be considered as leak.
Upvotes: 0
Reputation: 70929
The thread never terminates so the garbage collector will never free x
. However if you never really use x
it it might be optimized out. If you do use x this can not be a memory leak - you use the memory.
Upvotes: 5