Possible Duplicate:
Garbage Collection and Threads
I got this question in an interview:
Assuming we have multiple threads created, if one of the threads calls garbage collection, will the un-referenced objects in other threads be collected also?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes and no.
Yes. Objects are not "in threads" — there is a single object graph for all threads running in the program, so when GC happens, unreachable objects are collected regardless of which thread created them, or had local references to them.
No. When a thread calls
Runtime.gc()the VM is not obliged to actually do anything so it may be that no GC happens and no memory is collected. For example it has no effect when-XX:+DisableExplicitGCis specified at the command line.No. Even when a GC happens, not all unreachable objects that were only ever reachable from one thread’s stack will necessarily be collected since generational GCs only deal with a subset of the object graph, and if that subset happens to contain all the unreachable objects created by a particular thread then it is only coincidence.