• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and garbage collection

 
Micah Wedemeyer
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I create a Thread and do not maintain a reference to it like:
(new Thread()).start();
then what happens when that Thread's start() method returns? Will it get marked for garbage collection?
Thanks,
Micah
 
Thomas Smets
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all the code is incorrect

If I create a Thread and do not maintain a reference to it like:
(new Thread()).start();



Then no the Thread you instanciate is not ready for GC as soon as you quit the line invoking the start () but when the run method of the Runnable. The Thread instance & all the object it may refere may be marked for GC if they are not referenced by anything anymore...
Thomas,
 
Micah Wedemeyer
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I knew that Thread would do nothing, it was just an example. My actual object in my application is simply a subclass of Thread.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, objects may be garbage collected if and only if they are not reachable from any living threads. This means that threads are the starting points for defining what is reachable, and what isn't - and even if no other threads hold any references to a Thread object, once start() has been called it cannot be garbage collected until its run() method completes (whether it completes normally or abruptly).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!