What are memory leaks in Java?

In Java, a memory leak refers to a situation where objects that are no longer needed or intended to be used by a program are unintentionally kept in memory. The Java Virtual Machine (JVM) cannot garbage collect (release from memory) these objects because they still have active references to them, either directly or indirectly, which prevents them from becoming eligible for garbage collection.

Memory leaks can lead to a gradual consumption of system resources, such as heap memory, which may eventually cause the program to slow down, become unresponsive, or even crash when it runs out of available memory.

Causes of Java memory leaks

Common causes of memory leaks in Java include:

  • Unintentional object retention: Objects that are no longer needed are still referenced by other objects or data structures, preventing the garbage collector from reclaiming their memory.

public class ObjectRetentionExample {
private List<String> dataList = new ArrayList<>();
public void addToDataList(String data) {
dataList.add(data);
}
public List<String> getDataList() {
return dataList;
}
// In this example, the dataList object is retained even after it's no longer needed.
public static void main(String[] args) {
ObjectRetentionExample example = new ObjectRetentionExample();
example.addToDataList("Data 1");
example.addToDataList("Data 2");
// do some other tasks...
// The example object is no longer needed, but the dataList is still referenced,
// preventing it from being garbage collected.
// This can lead to a memory leak if this pattern continues.
}
}
  • Unclosed resources: Resources like files, network connections, or database connections are not properly closed after use, leading to resource leaks and associated memory leaks.

import java.io.*;
public class UnclosedResourceExample {
public static void main(String[] args) {
try {
// Open a file but forget to close it
File file = new File("example.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, World!");
// Missing writer.close(); statement
} catch (IOException e) {
e.printStackTrace();
}
// The file writer is not properly closed, causing a resource leak.
}
}
  • Listener and callback references: Registering listeners or callbacks without properly deregistering them can lead to memory leaks, as the listener objects remain in memory even if they are no longer needed.

import java.util.function.Consumer;
public class ListenerLeakExample {
private Consumer<String> callback;
public void registerCallback(Consumer<String> callback) {
this.callback = callback;
}
public void performTask(String data) {
// Do some task...
// Notify the callback with the result
callback.accept(data);
}
// In this example, if you register a callback and forget to deregister it,
// the listener object will be retained in memory even after it's no longer needed.
public static void main(String[] args) {
ListenerLeakExample example = new ListenerLeakExample();
// Register a callback but forget to deregister it later.
example.registerCallback(result -> {
System.out.println("Received result: " + result);
});
// Perform the task
example.performTask("Task data...");
// The example object is no longer needed, but the callback reference is still there,
// causing a memory leak if this pattern continues.
}
}
  • Static references: Objects stored as static variables can persist throughout the application's lifetime, causing them to be retained even when they are no longer necessary.

public class StaticReferenceExample {
// Static variable holding a reference to an object
private static List<String> dataList = new ArrayList<>();
public void addToDataList(String data) {
dataList.add(data);
}
public static void main(String[] args) {
StaticReferenceExample example1 = new StaticReferenceExample();
StaticReferenceExample example2 = new StaticReferenceExample();
example1.addToDataList("Data 1");
example2.addToDataList("Data 2");
// dataList is a static variable, so its reference will persist
// throughout the application's lifetime, even after the example1 and example2
// objects are no longer needed. This can lead to a memory leak.
}
}
Copyright ©2024 Educative, Inc. All rights reserved