Multithreaded garbage collection

Possible duplicate:
Garbage collection and themes

I got this question in an interview: Assuming we have multiple threads created, if one of the threads calls garbage collection, will the objects be collected without referencing the other threads?

+3


source to share


1 answer


Yes and no.

If one of the threads calls garbage collection, will unreferenced objects in other threads also be collected?

Yes. Objects are not "in threads" - there is one object graph for all threads running in a program, so when GC occurs, inaccessible objects are collected no matter which thread created them or have local references to them.



Not. When a thread calls Runtime.gc()

, the virtual machine is not required to actually do anything, so it may happen that no GC occurs and no memory collection is performed. For example, it has no effect when -XX:+DisableExplicitGC

specified on the command line.

Runtime.gc()

Calling this method suggests that the Java Virtual Machine wastes the effort of reusing unused objects in order to make the memory they are currently occupying for fast reuse.

Not. Even when a GC occurs, not all unreachable objects that are ever reachable from a single thread will necessarily be collected, since GC generating groups only deal with a subset of the object graph, and if that subset contains all unreachable objects created by a particular thread, then it's just a coincidence.

+10


source







All Articles