A simple java program that constantly uses memory

I have this simple Java code that creates one instance of a JFrame and displays it. This link contains a screenshot of the memory usage graph made by jconsole

enter image description here

My concern is that java.exe in the task manager shows that memory usage is constantly increasing at a speed of 4-5 kbps every 8-9 seconds. Help is needed

import javax.swing.*; class MyGUI extends JFrame { public void makeGUI() { setLayout(null); setSize(500, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } public class Launcher { public static void main(String []args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new MyGUI().makeGUI(); } }); } } 
+3
source share
3 answers

The profile looks completely normal - the program creates objects and from time to time the garbage collector frees up memory by disposing of objects that are not yet reachable.

The important point is that the trough points are more or less at the same level, so it doesn't seem like your code has memory management problems.

You can reduce the height of the peaks by setting the maximum amount of heap to a lower level, but 5 MB is not so much ...

+7
source

I think this memory is caused by the generation of objects used by swing, like various user interface events (mouse movement, etc.). Swing tends to generate objects for each event and invokes listeners that handle these events. After that, these event-related objects are no longer used (unless you are referencing them).

This is not a memory leak, this is normal behavior. In fact, in your screenshot of the memory consumption screen, memory drops sharply when the garbage collector releases these objects.

+4
source

Java tends to use memory on its own. This is not garbage to collect very often, and therefore it will naturally increase in size even with a simple program during operation. Since he should do classes for minor events that you do not even see basically.

You can always call System.gc() if you want to force java to collect garbage and reduce memory usage manually, but you should use it very sparingly.

0
source

All Articles