Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

GC - Thread safe

 
Radhakrishnan Ranjit
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is System.gc(); thread-safe? Please help

Thanks
RR
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sunny X Narula
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
Runtime.getRuntime().gc()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic