File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes GC - Thread safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "GC - Thread safe" Watch "GC - Thread safe" New topic

GC - Thread safe

Radhakrishnan Ranjit

Joined: Aug 12, 2009
Posts: 10
Is System.gc(); thread-safe? Please help

Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
Why would you care about Thread Safety if you run the Garbage Collector? It trashes objects that are no longer reachable by any references pointing to them.

JDBCSupport - An easy to use, light-weight JDBC framework -
Sunny X Narula

Joined: Dec 07, 2008
Posts: 22
As per my understanding the thread that run the GC is a JVM/System thread.
And the answer to the original question is system dependent i.e. the call to System.gc is actually a native call so it depends on the implementation.
But if you are really concerned with whether you should be careful about where you place this call. As per my understanding you do not need to.
Also you need to know that a call to the GC method does not ensure garbage collection. Read ahead for more info.

Extra Information:
To some extent you can control the behavior of the GC mechanism by using JVM options like UseParallelGC and UseSerialGC but I have not used them practically.

This is from the gc documentation:

public static void gc()
Runs the garbage collector.
Calling the gc 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. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:
I agree. Here's the link:
subject: GC - Thread safe
It's not a secret anymore!