Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this java process not release memory?

I have written a java application and I have run the java process under Fedora 24. Then I checked jconsole and found out that it uses around 5 to 10 megabytes of memory. The effect of garbage collection is also visible in the graph.

Here is the screenshot: jconsole screenshot

Then I checked my System Monitor and found out that the same process ID has more than 100 megabytes memory usage.

Here is the screenshot:

System Monitor screenshot

Please tell me why doesn't the process release unused memory?

Is there any way to release it?

like image 244
Matin Lotfaliee Avatar asked Jul 04 '16 18:07

Matin Lotfaliee


1 Answers

There is a difference between used heap and allocated heap. The blue line in your graph is the used heap - how much of the heap is actually holding objects. What is not shown is the size of the heap which is allocated - this is larger, often much larger, so that the JVM can allocate more objects without running out of space and having to go back to the OS for more memory (which is expensive). In your case, some of that 100mb which the system is showing is the JVM itself, but most of it is likely allocated but unused heap.

When you run a Java program without specifying the heap size you want it to use the JVM will try to figure out a sensible setting based on your machine, OS, JVM version etc. When I just ran a simple Hello World on my machine with 16GB of RAM and Java 8 it initially allocated 256mb for the heap. Obviously much more than it needs! If I wanted to force it to use less I can use the -Xms command line to set the initial heap allocation and -Xmx to set the maximum allowed. My guess is that if you set something like -Xms20m you'd see less memory being used by your process. In IntelliJ add that setting to the VM Options field in your run configuration.

like image 111
adamreeve Avatar answered Sep 22 '22 00:09

adamreeve