Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify memory leak in Java

From the question Creating a memory leak with Java there are many ways to create memory leaks in Java, but I am just trying to create a simple memory leak and being able to observe its effect somehow. In fact, after trying to create a memory leak I would like to verify that ( in numbers or something) so that I assure that the memory leak has been successfully created. Can we investigate the occurrence of memory leak in our code by not using a third party application, just by inserting e.g. runtime.maxMemory() in our code?

like image 286
C graphics Avatar asked Aug 29 '14 19:08

C graphics


People also ask

How do I check for memory leaks?

The primary tools for detecting memory leaks are the C/C++ debugger and the C Run-time Library (CRT) debug heap functions. The #define statement maps a base version of the CRT heap functions to the corresponding debug version. If you leave out the #define statement, the memory leak dump will be less detailed.

Do memory leaks exist in Java?

One of the core benefits of Java is the JVM, which is an out-of-the-box memory management. Essentially, we can create objects and the Java Garbage Collector will take care of allocating and freeing up memory for us. Nevertheless, memory leaks can still occur in Java applications.


1 Answers

This is a poor-man's substitute for a memory profiling tool:

public static long bytesOccupied() {
   final Runtime rt = Runtime.getRuntime();
   for (int i = 0; i < 2; i++) rt.gc();
   return rt.totalMemory()-rt.freeMemory();
}

I have used this on several occasions and can attest that it works at least on some setups. Try it and see if it gives sensible results for you.

Otherwise, it is really easy to start VisualVM, which is already installed on your computer with the JDK. Be sure to install the optional VisualGC plugin. Make your code do some allocations in a loop and watch the GC generations churn. Use a short sampling time (100 or 200 ms) to get a realtime feel.

like image 98
Marko Topolnik Avatar answered Oct 23 '22 14:10

Marko Topolnik