Are Memory Leaks Possible in Java?

This question already has an answer here:

  • Creating a memory leak with Java 52 answers

  • 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.

    链接地址: http://www.djcxy.com/p/3360.html

    上一篇: Java中有链表的快速concat方法吗?

    下一篇: Java中的内存泄漏可能吗?