GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — sample-java-programs/memoryleak at master · odissea/sample-java-programs

Expand file tree

/

memoryleak

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

memoryleak

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
src/main
src/main
 
 
README.md
README.md
 
 
pom.xml
pom.xml
 
 

README.md

Outline

Sample to show a memory leak in Java Application

This sample application implements a simple caching solution using a HashMap.

For example, see following code.

Map<Key, String> map = new HashMap<>();
while (true) {
    for (int i = 0; i < max; i++) {
        Key key = new Key(i);
        if (!map.containsKey(key)) {
            map.put(key, "Number:" + i);
        }
    }
}

The map is not expected to grow beyond max value as all keys will be there in the map after the first while loop.

However, if the Key class does not contain a proper equals() implementation along with the hashCode() implementation, the key elements will be keep getting added as the !map.containsKey(key) will always return false. This is a good example of a memory leak and this sample was inspired by the blog post: "How to create a memory leak"

How to run

The application will throw Out of Memory error after some time when you run following command

java -Xms1g -Xmx1g -XX:+PrintGCDetails -XX:+PrintGC -XX:+PrintGCDateStamps -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath="/tmp/heap-dump.hprof" -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=settings=profile,duration=5m,name=MemoryLeak,filename=memoryleak.jfr -XX:FlightRecorderOptions=loglevel=info -jar target/memoryleak.jar

Analyzing Java Flight Recording

In Memory -> Memory tab, you should see a high memory growth rate.

Also see Memory -> Garbage Collections tab and check the frequency of GC events.

Analyzing Garbage Collection Logs (GC)

You can analyze the GC logs using GCViewer

How to fix the Memory Leak

Run the application with --key-type GOOD parameter, which will use a Key object with proper equals() implementation.

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.