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?
Warren Dew
8,9383 gold badges34 silver badges44 bronze badges
asked Jun 26, 2016 at 6:48
amrender singh
8,2594 gold badges27 silver badges30 bronze badges
1 Answer 1
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.
answered Jun 26, 2016 at 6:57
Mureinik
316k54 gold badges404 silver badges406 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Sharon Ben Asher
why do you need user input? a
LEAK.add("str"); inside while(true) would sufficeMureinik
@sharonbn indeed. This example just seemed somewhat palatable, but, ultimately, there's nothing special about it, and there could be a gazilion different examples.
Explore related questions
See similar questions with these tags.
lang-java