DEV Community

Cover image for How to Save RAM in Java with G1 Garbage Collector
Petr Filaretov
Petr Filaretov

Posted on

How to Save RAM in Java with G1 Garbage Collector

In the cloud world, you often pay only for what you actually use. So, you want to minimise the resources consumed. And here is one of the tips to save RAM in Java with G1 garbage collector.

If the application is idle most of the time and only runs memory-intensive operations once in a while, then it may not release the memory between operations that could actually be released. This is because garbage collection will not be triggered if there are no heap or object allocations happening.

Here is an example:

public class DeepThought {
    public static void main(String[] args) {
        System.out.println("Press Enter to start...");
        new Scanner(System.in).nextLine();

        calculateTheAnswer();

        System.out.println("Press Enter to exit...");
        new Scanner(System.in).nextLine();
    }

    private static void calculateTheAnswer() {
        System.out.println("Calculating The Answer...");
        for (int i = 0; i < 500; i++) {
            int[] array = new int[1_000_000];
        }
        System.out.println("The Answer is... 42.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here the main() method waits for user input to start memory-intensive processing (calculateTheAnswer()) and then waits for user input again to complete. These two user inputs are just for convenience so that it is easy to attach to the running program with VisualVM and see what is going on.

Let's run it with -XX:+UseG1GC, attach VisualVM, and press Enter to start processing. The memory consumption will look something like this:

Memory consumption 1

The heap grows during calculateTheAnswer() execution and does not shrink after that. And here is the chart after some time:

Memory consumption 2

The garbage collection happened after 1 hour and 15 minutes when the used heap reached the heap size. However, even after that, the heap size did not shrink. Furthermore, it is increased!

During another run of the same program, you can get something like this:

Memory consumption 3

Funny, doesn't it?

So, how can we deal with that?

Java 12 introduced the -XX:G1PeriodicGCInterval VM option. It defines a minimum interval in ms at which G1 considers performing a garbage collection.

Now, let's run the program again with the following VM arguments:

-XX:+UseG1GC -XX:G1PeriodicGCInterval=5000
Enter fullscreen mode Exit fullscreen mode

Now, the memory consumption will look something like this:

Memory consumption 4

Here we can see that G1 triggered additional garbage collection, and the heap size shrunk significantly after the processing is done.


Dream your code, code your dream.

Top comments (0)