Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.gc() calls by core APIs

Some of you probably know that some of core java APIs make explicit calls to System.gc(). I know two cases when this happens:

  1. NIO. I believe that is done to do some cleanup for direct ByteBuffers, when system runs out of "direct" memory.
  2. RMI. Here, the reason is not that clear for me...

So, questions are:

  1. Do know reason why System.gc() is required for RMI?
  2. Do you know any other situations when core APIs (or even some other popular libraries) can make a direct call to System.gc()?
like image 518
Stas Avatar asked Aug 04 '11 12:08

Stas


People also ask

What happens when we call system gc ()?

gc() method runs the garbage collector. Calling this 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.

Is it good to call system gc Java?

gc() may do nothing, and that any code that "needs" the garbage collector to run is broken. However, the pragmatic reason that it is bad practice to call System. gc() is that it is inefficient.

What does system gc () and runtime gc () methods do?

System gc and Runtime gc are two methods to request JVM to run Garbage collector. The basic difference between System gc and Runtime gc in Java is that System gc is a class method while Runtime gc is an instance method.

Does system gc calls Finalize?

System. gc() is what you call when you want Java's garbage compiler to run. It will run by itself every few minutes, but you can ask it to go whenever you want. When the garbage collector runs, it calls the finalize() method on each object that has no more reference.


1 Answers

RMI calls the System.gc() in case there are distributed objects which need to be cleaned up. You can make it perform GC less often or effectively turn it off.

You can avoid direct ByteBuffer needing a GC to clean them up on the Sun/Oracle JVM by calling

ByteBuffer bb = ByteBuffer.allocateDirect(SIZE);
((DirectBuffer) bb).cleaner().clean();
like image 50
Peter Lawrey Avatar answered Sep 22 '22 11:09

Peter Lawrey