2

I'm starting my thread like so:

(new MyThread()).start();

I'm not keeping a reference to it anywhere, so I'm wondering if it's a safe approach - can't GC collect it since it's not referenced?


If not (I think so), then why?

MightyPork
  • 18,270
  • 10
  • 79
  • 133
  • GC can collect them, just make sure the code in `run` method finishes correctly. Also, use `ExecutorService` instead of using plain `Thread`s naively. – Luiggi Mendoza Apr 04 '14 at 22:56
  • Today i had same question in my MIND!!! :) – Tomas Bisciak Apr 04 '14 at 22:56
  • @LuiggiMendoza that's not what I meant, anyway, could you explain why is ExecutorService better than this? Advantages? – MightyPork Apr 04 '14 at 22:59
  • The *thread* (the actual thread) is [it's *own* GC root](http://stackoverflow.com/a/2423293/2864740). – user2864740 Apr 04 '14 at 22:59
  • possible duplicate of [Java Thread Garbage collected or not](http://stackoverflow.com/questions/2423284/java-thread-garbage-collected-or-not) – user2864740 Apr 04 '14 at 23:00
  • Read here: [When should we use Java's Thread over Executor?](http://stackoverflow.com/q/1094867/1065197), when you may infer from all the answer that `ExecutorService` provides a better interface to work with concurrency than using threads alone. – Luiggi Mendoza Apr 04 '14 at 23:02
  • Thread and ExecutorService serve different purposes. Create a Thread when you need a long running task that _waits_ for something (e.g., waits for keyboard input, waits for network connections) Use an ExecutorService when you want to parallelize a computation that can be broken up into two or more finite tasks. – Solomon Slow Apr 05 '14 at 18:07

1 Answers1

5

If you look at the OpenJDK Java 7 source code of Thread, you'll notice that start() contains the following

group.add(this);

where group is the Thread's ThreadGroup which is managed by the JVM. So there is always a reachable reference to the Thread while it is still running. It won't be garbage collected


If this alone isn't convincing, consider that starting a new thread means creating a new call stack where the root call is one of Thread's methods, probably some native method. You can't be executing the method of an object if the object is garbage collected. As such, the Thread object must still be alive.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724