Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is GC collecting here?

This might be pretty basic, but was very curious to know. Here's the code snippet and the output

public class PlainSystemGC {

    public static void main(String ...strings) {

        System.out.println("Free Memory (Before GC): " + Runtime.getRuntime().freeMemory());

        System.gc();

        System.out.println("Free Memory (After GC): " + Runtime.getRuntime().freeMemory());
    }
}

and the output

Free Memory (Before GC): 1859640
Free Memory (After GC): 1911768

I am interested to know what is GC collecting here since no objects are created.

What's the memory thats being freed up ? ( and that too 52kb )


@JSauer - It gives Exactly the same results even if run 100 times

like image 468
JWhiz Avatar asked Aug 05 '10 16:08

JWhiz


People also ask

What does GC collect do?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

What is GC collect () Python?

The garbage collector is keeping track of all objects in memory. A new object starts its life in the first generation of the garbage collector. If Python executes a garbage collection process on a generation and an object survives, it moves up into a second, older generation.

When GC collect is called?

One useful place to call GC. Collect() is in a unit test when you want to verify that you are not creating a memory leak (e. g. if you are doing something with WeakReferences or ConditionalWeakTable, dynamically generated code, etc).

Should you use GC collect?

GC. Collect() should not be called for the purpose of "quickly clean up the unused memory immediately". Having a forced release of memory does not pay off the overall performance caused by an active garbage collection. Save this answer.


1 Answers

On most JVM implementations the main method is not actually the first piece of Java code that is run during the JVM startup.

Usually, many parts of a complete JRE are themselves implemented in Java. For example a big part of the classloader mechanism is implemented in pure Java. It might even be able to write parts of the garbage collection algorithm itself in Java.

Due to this, there may already be some garbage from those system classes that the gc can collect even if your application created no garbage at all.

By the way, your application creates at least one object that is eligible for garbage collection at the point where System.gc() is called: The String that mentions the free memory is constructed dynamically and not held in a variable, so it could well be gc-ed during the System.gc() call.

like image 96
Joachim Sauer Avatar answered Sep 30 '22 01:09

Joachim Sauer