Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

How to find and fix memory leaks in your Java application

August 14, 2014
Leo Ufimtsev
Related topics:
Linux
Related products:
Red Hat Enterprise Linux

    Memory increase

    Do you have a Java application that runs fine at first but slows down after a while, or it runs fine for a small number of files but performance degrades for large number of files? Maybe you have a memory leak.

    About

    When fixing memory leaks; If someone were to ask me: "If you knew back then what you know now, what would you tell yourself?". Well, I would say.....

    Target Audience

    While in general the approach described in this article is IDE & OS independent, I used Linux [Fedora] and Eclipse [Plugin development] in the screenshots & instructions.

    Symptoms of a Memory leak

    Works fast at first, but slows over time.

    •  Works fine with small data sets, severe performance issues with large data sets
    •  Ever increasing Old-Generation memory usage in your JVM
    •  Out-of-Memory Heap errors in your JVM
    •  Spontaneous crashes.

    Common Memory leaks

    A memory leak in Java (who would've thought heh?) can occur if you forget to close a resource, or a reference to an object is not released. e.g.

    • File/Text buffers not closed. (as was in my case)
    • Hash maps keeping references alive if equals() and hashcode() are not implemented, e.g.
    • import java.util.Map;
      public class MemLeak {
      public final String key;
      public MemLeak(String key) {
          this.key = key;
      }
      
      public static void main(String args[]) {
          try {
            Map map = System.getProperties();
            for(;;) {
               map.put(new MemLeak("key"), "value");
            }
          } catch(Exception e) {
              e.printStackTrace();
          }
        }
      }

      details.... 

    •  Inner classes that reference outer classes can leak. (make them static to avoid).

    How does one go about fixing them?

    There are two approaches. The first is a 'quick fix' attempt. If that fails then you'll have to go down the long road.

    • 1) Quick fix: Eclipse Memory Leak Warnings (catches some leaks)
    • 2) Manually disable & enable parts of your code and observe memory usage of your JVM using a JVM tool like VisualVM (or Jconsole, or Thermostat).

    1) Quick fix: Eclipse Memory Leak warning/errors.

    For code with JDK 1.5+ compliance, eclipse will throw warnings and errors at you for obvious cases of leaks. To be more precise, anything that implements closable (since 1.5) (e.g outputstream since 1.5) will throw a warning at you if its reference is destroyed but the object is not closed. However, the leak-detection isn't always enabled in eclipse projects. You might have to turn them on first. Go to your project settings and enable them as demonstrated:

    Enable Leak detection in eclipse

    Now eclipse will outline memory leaks:

    Potential Memory leak

    However, even with fancy Eclipse hocus pocus, not all file closures and leaks are detected. Especially when working with legacy (pre 1.5) code, you'll likely run into leaks because those were written before 'closable' was implemented. Or sometimes file opening/closures are nested so deeply that eclipse won't detect them.  If you're in this place, you may want to try step 2.

    2) Manually disable & enable parts of your code and observe memory usage of your JVM using a JVM tool like VisualVM.

    If you got this far then you'll have to roll up your selves and do some manual labor. You could read all of your code and try to understand where the leak occurs. To help you with this process: I recommend to try using a tool like VisualVM.  (But Thermostat and MAT also work.)

    Configure VisualVM

    1. Download the tool
    2. Open terminal, navigate to .../visualvm_xyz/bin run the shell script './visualvm'   (or visualvm.exe on windows).
    3. You should see the main window.  If you expand 'local' and double click on your running application (a child eclipse in my case), you can see its properties. visual vm main
    4. Troubleshooting VisualVM on Fedora (skip this if it works well:  For me, initially I couldn't connect to my JVM's, I couldn't take heap-dumps and profiling didn't work either. Here are some steps that might help:
      • Make sure that you run it as your own user and not sudo.
      • Perform a full update of your system (sudo yum update).
      • Reboot helps :)
      • Try to close all running Java applications. Launch VisualVM, then try your luck again.
    5. Add some plugins. Before VisualVM became useful to me, I first had to add some plugins. Go to Tools -> Plugins -> 'Available Plugins'. Select these plugins (feel free to browse and add more if you like):
      • Memory Pools
      • Visual GC
      • Kill Application

    Analyze running code with visualvm

    1. Now run your Java application,
    2. Attach VisualVM to your application.
    3. Perform the operation that causes the sluggish performance.
    4. Inspect the 'Monitor' and the 'memory pools' tab. If you see that your memory increases in the 'Monitor' tab, try  pressing 'Perform GC' (garbage collection) and see if that decreases memory usage.   Copyright out of memory _ANNO If not...
    5. Then switch over to the 'memory pools' tab and inspect the 'Old Gen'. (Objects first hang around in "Eden", then transition through Survivor spaces, older objects move into the 'Old Gen' Pool. If something leaks, it'll be in the Old-Gen pool. Details) Visual Vm meam leak _anno
    6. Now go back and comment out most of the code of your program to the point where the application just start & stops.
    7. Repeat until the application doesn't leak at all.
    8. Then through several iterations re-enable parts of your code and inspect VisualVM memory usage. When your application starts to leak again, go into the method that caused the memory leaks and narrow down further.
    9. Eventually you'll narrow down the problem to a single class, perhaps even a single method. Once you're there, carefully validate that all file-buffers are closed and Hashmaps are used properly.

    Benchmarking your code

    Sometimes it's hard to tell if your shiny new code is any better than the old code. In this case you may want to benchmark the performance of your application. Here is some code that you can insert into the right place to get info about run-time and number of garbage collection runs:

    long start = System.currentTimeMillis();
    ..
     //your code
    ..
    long end = System.currentTimeMillis();
    System.out.println("Run time: " + Long.toString(end - start));
    System.out.println(printGCStats());
    
    public static String printGCStats() {
     long totalGarbageCollections = 0;
     long garbageCollectionTime = 0;
     for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
     long count = gc.getCollectionCount();
    
     if (count >= 0) {
     totalGarbageCollections += count;
     }
    
     long time = gc.getCollectionTime();
    
     if (time >= 0) {
     garbageCollectionTime += time;
     }
     }
     return "Garbage Collections: " + totalGarbageCollections + "n" +
     "Garbage Collection Time (ms): " + garbageCollectionTime;
    }

    As a note, if you test in your main Eclipse, it's recommended to test in a 'clean' child Eclipse instead. Or in some 'clean' instance of your Eclipse, because other plugins will get in the way of accurate timing.

    Additional help: Heap dumps

    I personally haven't used this much, but folks rave about 'Heap-dumps'. At any time, you can take a heap-dump and then see how many  instances of classes are open and how much space they utilize. You can double click on them to see their content. This is useful if you want to see how many objects your application generates.

    Visual Vm Heap dump _Anno

    Hold on, my application doesn't have leaks but it's still slow?

    It's possible that you don't have any leaks in your code, but it's still very slow. In this case you'll have to profile your code. Code profiling is out of the scope of this article, but there is a great youtube lecture that explains how you can profile with Eclipse using free and paid profilers.

    Where to go from here?

    At this stage, try to spend a day or two actually fixing your memory leak. If you still have troubles, try reading some of these articles:

    • Hunting Memory Leaks
    • Memory leaks in Inner classes and this is also useful.
    • The profiling youtube lecture mentioned above
    • Skim over oracle's JVM GC guide.

     

    Last updated: February 22, 2024

    Recent Posts

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.