0

After instantiating a Thread and start it what will happened to the created instance of it. Will it have same behavior as other instance?

Thread a = new MyThread();
a.start();

a = null

where this created instance of Thread resides(in heap or doesn't it be in tenured space). will it be garbage collected?. If it is get garbage collected what happened to used instance properties?

asela38
  • 4,546
  • 6
  • 25
  • 31
  • just... think. What would happen if it DID get garbage collected? It would be awful and no decent language designer would let that happen. (to state it with fool-proof explictness: it doesn't get garbage collected until it is no longer referenced, and it is referenced until the thread ends) – amara May 16 '11 at 04:55
  • 1
    possible duplicate of [Java Thread Garbage collected or not](http://stackoverflow.com/questions/2423284/java-thread-garbage-collected-or-not) – Stephen C May 16 '11 at 04:55
  • referenced by whom in this case – asela38 May 16 '11 at 04:57
  • What do you mean by 'created instance' and 'other instance'? – user207421 May 16 '11 at 06:17

2 Answers2

1

A thread will not be garbage collected while it is "live", irrespective of whether the Thread object can be accessed. This is a consequence of the JLS's definition of reachability.

For the record, a typical JVM allocates a thread's stack in memory that is outside of the heap(s). The Thread object and its children are regular heap objects. These may be garbage collected: the specifications are silent on this, AFAIK. Finally, part of a thread's state may reside in memory managed by the OS kernel.


when I view the JVM through the JProfiler I was unable to find the instance of the MyThread which I create.

  1. That doesn't prove that it has been garbage collected. All it proves is that JProfiler couldn't find it.

  2. If the thread has terminated (and you haven't kept a reference to the Thread object) then it / they will no longer be reachable, and JProfile won't be able to find it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • when I view the JVM through the JProfiler I was unable to find the instance of the MyThread which I create – asela38 May 16 '11 at 04:55
0

By very definition, the Thread object is reachable by it's own thread as long as that thread is alive - so clearly, no, the Thread object will not be GC'd at least until the thread which was started lives.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189