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?
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?
Yes and no.
if one of the threads calls garbage collection, will the un-referenced objects in other threads be collected also?
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:+DisableExplicitGC
is specified at the command line.
Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.
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.