Are Memory Leaks Possible in Java?
This question already has an answer here:
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.
下一篇: Java中的内存泄漏可能吗?