How can I create a memory leak in Java?

后端 未结 30 1772
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 22:26

I just had an interview, and I was asked to create a memory leak with Java.

Needless to say, I felt pretty dumb having no clue on how to eve

30条回答
  •  难免孤独
    2020-11-21 22:56

    You can create a moving memory leak by creating a new instance of a class in that class's finalize method. Bonus points if the finalizer creates multiple instances. Here's a simple program that leaks the entire heap in sometime between a few seconds and a few minutes depending on your heap size:

    class Leakee {
        public void check() {
            if (depth > 2) {
                Leaker.done();
            }
        }
        private int depth;
        public Leakee(int d) {
            depth = d;
        }
        protected void finalize() {
            new Leakee(depth + 1).check();
            new Leakee(depth + 1).check();
        }
    }
    
    public class Leaker {
        private static boolean makeMore = true;
        public static void done() {
            makeMore = false;
        }
        public static void main(String[] args) throws InterruptedException {
            // make a bunch of them until the garbage collector gets active
            while (makeMore) {
                new Leakee(0).check();
            }
            // sit back and watch the finalizers chew through memory
            while (true) {
                Thread.sleep(1000);
                System.out.println("memory=" +
                        Runtime.getRuntime().freeMemory() + " / " +
                        Runtime.getRuntime().totalMemory());
            }
        }
    }
    

提交回复
热议问题