Results 1 to 9 of 9
  1. #1
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Memory Managment/Leaks

    Hello everyone..

    I have a simple question I guess which I can't explain it somehow, maybe because I don't really know all the mechanics off java I mean in low lever. I created an application for a customer and I was just playing around with it when I decided to check about how much Memory ram does it needed and while I was navigating through the app menu and different frames/scenes I saw that in every step I made the memory usage by the programs was increasing and never goes back down.. So that makes me wondering.. What is really happening? There is something wrong with my program or has something to do with how java works.. So I created the most silly program that I can imagine that can illustrate my case . The program is just a JFrame holding JTabbedPane with 2 tabs which each tab has a panel and a label inside it nothing more nothing less. So here is the code :

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.SwingUtilities;
    
    @SuppressWarnings("serial")
    public class LeaksTester extends JFrame {
    	public static final int WIDTH = 500;
    	public static final int HEIGHT = 400;
    	
    	public LeaksTester(){
    		setSize(new Dimension(WIDTH,HEIGHT));
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLocationRelativeTo(null);
    		setLayout(new BorderLayout());
    		initComponents();
    	}
    	
    	
    	private void initComponents() {
    		JTabbedPane tabbedPane = new JTabbedPane();
    		
    		JPanel panel1 = new JPanel();
    		JPanel panel2 = new JPanel();
    
    		JLabel label1 = new JLabel("Label 1");
    		JLabel label2 = new JLabel("Label 2");
    		
    		panel1.add(label1);
    		panel2.add(label2);
    
    		tabbedPane.addTab("Panel 1", panel1);
    		tabbedPane.addTab("Panel 2", panel2);
    		this.add(tabbedPane,BorderLayout.CENTER);
    	}
    
    
    	public static void main(String[] args) {
    		SwingUtilities.invokeLater(new Runnable() {
    
    			@Override
    			public void run() {
    				JFrame frame = new LeaksTester();
    				frame.setVisible(true);
    			}
    		});
    	}
    }
    Now when I first compile and run this program I check it's memory usages from Window's tasks manager and it had 22.704k so I start to change between tabs with no reason for like 50 times and pouf the memory has grown to 34.568K so in order to be sure that will be somehow a problem I used a autoclicker and makes it to switching between tabs for like 5 minutes rabidly and the result was : 53.996k

    Of course I thought well it might be because there is too much over head right now.. Let it relax for some minutes and I am sure will fix it and turn in back to some more reasonable value like 22-30MB but after passing 10 minutes doing nothing the memory was still the same.. I tried to increase it farther but for some reason it stuck on 54.032K

    Well of course I am not going to worrying about 50 or 100 MB but when
    My main program starts from 130 and just playing around for some time goes to 450+ it's starts making me worried. What if I want my program to be open for hours or even forever? It will stuck too in some high value or it will crash? What exactly is happening behind the scenes? I am really sorry if this question it's a silly one..

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Memory Managment/Leaks

    The JVM doesn't really care about garbage collecting until memory is getting depleted. Try adding a button that has System.gc() in its ActionListener. The application will tell the VM to garbage collect and the memory will go down.

    Having said that, the Windows Task manager is the worst profiling tool ever. Try using the jVisualVM tool in the jdsk/bin directory, and play with the buttons a bit. See screenshot below.


    Memory Managment/Leaks-heap.png
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Re: Memory Managment/Leaks

    The JVM doesn't really care about garbage collecting until memory is getting depleted
    This is quit interesting... So if a understand you correctly it doesn't need to do anything at all cause if the memory is getting depleted the app will automatically call System.gc() by itself. I always thought that calling System.gc() is a bad practice cause calling it can add unnecessary performance , and it is not guaranteed to actually perform a collection. JVisualVM hmm to Be honest i didn't knew that this kind of program was existed.. Nice

    Now let's say for a moment that calling System.gc() it might helps , so I have to find a good moment to call it once in awhile or it doesn't really matter? I am using a lot of different external APIs so calling System.gc() while some of those tasks is still going on might cause any problem or it doesn't affect it at all?

    Even thought I am going to have a look at JVisualVM with my main app and see what is going on. I might find some other software (Google is a good friend :P ) about checking for memory leaks etc. Again thanks you ... 'The JVM doesn't really care about garbage collecting until memory is getting depleted' was all I needed.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Memory Managment/Leaks

    Stick with the "don't call gc() directly".

    The times you might need to you'll be doing something incredibly specialised anyway that you'll know it when you see it.

    Also, remember that the JVM doesn't hand memory back to the underlying system all that often.
    A gc run only frees up heap, but that heap is still owned by your Java process, so the task manager will still class it as being used.

    So in your example, Task Manager might be showing 50Mb being used, but from the JVM's point of view most of that is free heap space.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Memory Managment/Leaks

    I only threw in System.gc() so you can see what happens to the memory. I never recommended using it as a one stop memory solution. Don't use gc(), only to see the gears moving in your favourite profiler.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Memory Managment/Leaks

    This doesn't account for all the memory used but it does illustrate Toll's point.
    The first column is the maximum amount of memory available to the JVM for your process.
    The second column is the maximum current heap size.
    The third column is available memory from the heap space.

    Notice that the heap will eventually increase to meet demands. But when the memory is gc'd the
    heap space retains its new maximum. So it might appear as though you have a memory leak.

    Java Code:
    import java.util.ArrayList;
    import java.util.List;
     
    public class MemoryCheck {
     
       private List<Object>    mem    = new ArrayList<>();
       private static Runtime        rt    = Runtime.getRuntime();
       public static void main(String[] args) {
          showMem();
          new MemoryCheck().start();
       }
       public void start() {
          for (int j = 0; j < 20; j++) {
             mem.add(new byte[1_000_000]);
             showMem();
          }
          mem.clear();
          System.gc();
          showMem();
       }
     
     
       public static void showMem() {
          System.out.printf("%,d     %,d     %,d%n",
                rt.maxMemory(),
                rt.totalMemory(),
                rt.freeMemory());
     
       }
    }
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Re: Memory Managment/Leaks

    Thank you all for the useful information you provided me...

    Also, remember that the JVM doesn't hand memory back to the underlying system all that often.
    So is it possible to tell the JVM (programmatically) to release the unnecessary memory that is been held by the process ? And if so.. How 'good' or maybe better how safe that will be?

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Memory Managment/Leaks

    There may be some switches you can apply to the JVM, but you'd have to look that up.

    The JVM doesn't hand back memory as grabbing more is time consuming.
    What you should be doing is sizing your app and then giving enough memory for it to run at peak and leave it at that.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Re: Memory Managment/Leaks

    Very well thanks for the advices!! and thank you all for your time :)

Similar Threads

  1. memory leaks in Java
    By Navatha in forum New To Java
    Replies: 8
    Last Post: 09-29-2010, 06:42 PM
  2. good memory managment
    By itaipee in forum New To Java
    Replies: 1
    Last Post: 12-15-2009, 10:44 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •