Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Memory Leaks in Java

4 min readJun 7, 2020

--

Press enter or click to view image in full size

In this story we are going to see what is memory leak, garbage collector, examples of leaks in Java and tools to detect leaks.

One of the key benefits of Java is that memory management is mainly handled by Java Virtual Machine or more specific Java Garbage Collector (GC). Java Garbage Collector is responsible for allocation and deallocation of objects on Heap.

What is Memory Leak

In computer science, memory leak means that computer programs incorrectly manage memory allocation by not releasing resources that are not needed. In Java, Memory Leak occurs when an object is no longer being used by an application, but Garbage Collector is not able to remove it from working memory (Heap). In the long run, accumulating objects and not being able to remove them leads to the OutOfMemoryError

Why Object is not Garbage Collected

Whether an object will be removed from working memory depends on the object type. There are two types, referenced and unreferenced. Objects that are unreferenced are periodically collected by GC, on the other hand objects that have a valid reference cannot be collected by GC.

Take a look at the picture below for better understanding.

Also, there are four types of references in Java that you can use to manage how and when GC to collect objects.

  • Strong Reference — This is the default object reference. Object that has a strong reference cannot be collected unless reference points to null.
  • Soft Reference — Object referenced using java.lang.ref.SoftReference class won’t be collected even if object is free for GC. Once the JVM needs memory, GC is required to clear all SoftReference.
  • Weak Reference — Object referenced using java.lang.ref.WeakReference class will be marked for GC if JVM detects that no strong or soft references are linked to any object.
  • Phantom Reference — Object referenced using java.lang.ref.PhantomReference are not automatically cleaned by GC, it needs to be cleaned up manually. After finalize method of its referent is executed, phantom reference is put to the reference queue.

What is Garbage Collector

Garbage Collector is a JVM daemon thread that periodically collects unreferenced objects from Heap memory. When an object is not referenced anymore it becomes eligible for eviction from heap memory. Heap memory is separated into three major areas: Young Generation (Eden Space, S0 Survivor Space and S1 Survivor Space), Old Generation and Permanent Generation.

Get Milan Adamovic’s stories in your inbox

Join Medium for free to get updates from this writer.

Also there are four types of Garbage Collector: Serial Garbage Collector, Parallel Garbage Collector(Default JVM GC), CMS Garbage Collector, and G1 Garbage Collector.

Difference between Garbage Collectors:

  • Serial Garbage Collector is designed for a single threaded environment, it uses single thread for collecting objects. This GC is suitable for command line applications and is enabled by using -XX:+UseSerialGCJVM argument.
  • Parallel Garbage Collector is default JVM Garbage Collector, unlike serial GC, parallel GC uses multiple threads to collect unreferenced objects from working memory.
  • CMS Garbage Collector or Concurrent Mark Sweep Garbage Collector uses multiple threads to collect unreferenced objects and it is designed for application that prefer shortened GC pauses. To enable CMS Garbage Collector use -XX:UseConcMarkSweepGC JVM argument.
  • G1 Garbage Collector is used for a large heap area. It uses techniques to separate Heap memory into regions and does object collection in parallel. To enable G1 GC use-XX:+UseG1GCJVM argument.

Example of Memory Leak

To reproduce memory leak faster and only for example I will lower the heap size to 125MB using JVM argument -Xmx125m

One of the most common scenarios for memory leak is referencing a heavy collection of elements as a static field. Let’s take a look at example:

private static final List<String> listOfStrings = new ArrayList<>(100000);

public static void main(String[] args) {
fillStaticList();

try {
Thread.sleep(100_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private static void fillStaticList() {
for (int i = 0; i < 100000; i++) {
listOfStrings.add("Some large text + " + i);
}
}
Press enter or click to view image in full size

Static collection will never be collected by GC during the JVM process lifetime. Now I will declare heavy collection as local variable in the example:

public static void main(String[] args) {
fillLocalList();

try {
Thread.sleep(100_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private static void fillLocalList() {
List<String> listOfStrings = new ArrayList<>(100000);
for (int i = 0; i < 100000; i++) {
listOfStrings.add("Some large text + " + i);
}
}
Press enter or click to view image in full size

And as you can notice from the profiler, once the method finishes execution collection is being removed by GC.

Java Profilers

Java Profiler is a tool for monitoring operations at the JVM level. There are many available Java Profilers, some of the most popular are YourKit, JProfiler and VisualVM.

--

--