Possible Duplicate:
Java Thread Garbage collected or not
Consider the following class:
class Foo implements Runnable { public Foo () { Thread th = new Thread (this); th.start(); } public run() { ... // long task } }
If we create several instances of Foo
by doing
new Foo(); new Foo(); new Foo(); new Foo();
(note that we don't keep a pointer to them).
Could those instances be removed by the garbage collector before the thread in run()
ends? (In other words: is there any reference to the Foo
objects?)
And, in the other hand, will those instances be removed by the GC after the thread in `run()' ends, or are we wasting memory ("memory leak")?
If either 1. or 2. are a problem, what's the right way to do it?
Thanks
Active Java Threads: Active Java threads join the garbage collection roots list because they are regarded as live threads. Static Variables: Static variables are referenced into classes; therefore, these garbage collector roots cannot be subject to clearance when the class is loaded.
Blocking during background - background GC does not suspend other threads during Gen2 collections. Nevertheless,Gen0 and Gen1 collections (which are an inevitable part of a full GC) still require managed threads to be suspended.
Yield that ZGC unexpectedly has higher throughput and longer total execution time than G1GC, and other attributes are in line with expectations. According to the results, ZGC has a better overall performance than G1GC under the testing circumstances.
No thread (or the things it refers to) will be garbage-collected while it is still running. Save this answer.
- Could those instances be removed by the garbage collector before the thread in run() ends? (In other words: is there any reference to the Foo objects?)
No. While the constructor is running GC won't collect the object. Otherwise even the simplest:
Customer c = new Customer();
could fail while the constructor of Customer
is running. On the other hand when you start a new thread, the thread object becomes a new GC root, so everything referenced by that object is not a subject to garbage collection.
- And, in the other hand, will those instances be removed by the GC after the thread in `run()' ends, or are we wasting memory ("memory leak")?
Once the thread is done, it is no longer a GC root. If no other code points to that thread object, it will be garbage collected.
- If either 1. or 2. are a problem, what's the right way to do it?
Your code is just fine. However:
starting a new thread in a constructor is a poor idea from unit-testing point of view
keeping a reference to all running thread might be beneficial if e.g. you want to interrupt these threads later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With