在Java 8中创建内存泄漏

同样的问题已经得到了回答(用Java创建内存泄漏),但现在Java 8删除了永久代。我认为更新这个主题将是有用的,因为大多数答案都依赖于耗尽永久代的空闲空间。

那么,在Java 8中创建内存泄漏的最简单方法是什么?


我认为一个普通的内部类内存泄漏会起作用。 取自互联网的示例:

public class LeakFactory
{//Just so that we have some data to leak
    int myID = 0;
// Necessary because our Leak class is non-static
    public Leak createLeak()
    {
        return new Leak();
    }

// Mass Manufactured Leak class
    public class Leak
    {//Again for a little data.
       int size = 1;
    }
}

public class SwissCheese
{//Can't have swiss cheese without some holes
    public Leak[] myHoles;

    public SwissCheese()
    {
    // let's get the holes and store them.
        myHoles = new Leak[1000];

        for (int i = 0; i++; i<1000)
        {//Store them in the class member
            myHoles[i] = new LeakFactory().createLeak();
        }

    // Yay! We're done! 

    // Buh-bye LeakFactory. I don't need you anymore...
    }
}

这里发生的是createLeak()工厂方法返回Leak类,理论上LeakFactory对象有资格被GC删除,因为我们不会引用它。 但Leak类需要LeakFactory才能存在,因此LeakFactory永远不会被删除。 无论您使用什么Java版本,这都会造成内存泄漏。

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

上一篇: Create a memory leak in Java 8

下一篇: Memory leak in java ImageIO.read()