7

I just had an interview, and I was asked if it was possible to have a memory leak in Java. I didn't know the answer. So I would like to know:

  • How would it be possible?
  • What would be an example of it?
  • Is it still possible even when Java uses Garbage Collection?
0

1 Answer 1

4

A memory leak, in the broader sense, is any situation where you continue to hold on to allocated memory you no longer need and no longer intend to use.

Consider the following [admittedly artificial] example:

public class LeakingClass { private static final List<String> LEAK = new ArrayList<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("What is your name? "); while (in.hasNext()) { name = in.next(); System.out.println("Hi " + name); LEAK.add(name); System.out.println("What is your name? "); } } } 

The LEAK list is grows in every iteration, and there's no way to free it up, yet it's never used. This is a leak.

Sign up to request clarification or add additional context in comments.

2 Comments

why do you need user input? a LEAK.add("str"); inside while(true) would suffice
@sharonbn indeed. This example just seemed somewhat palatable, but, ultimately, there's nothing special about it, and there could be a gazilion different examples.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.