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?
Warren Dew
  • 8,790
  • 3
  • 30
  • 44
amrender singh
  • 7,949
  • 3
  • 22
  • 28

1 Answers1

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • why do you need user input? a `LEAK.add("str");` inside `while(true)` would suffice – Sharon Ben Asher Jun 26 '16 at 07:05
  • 1
    @sharonbn indeed. This example just seemed somewhat palatable, but, ultimately, there's nothing special about it, and there could be a gazilion different examples. – Mureinik Jun 26 '16 at 07:06