Create a memory leak in Java 8
The same question has been answered again (Creating a memory leak with Java) but now that Java 8 removed the Permanent Generation I think that it would be useful to update this topic since most of the answers depend on exhausting the free space of the Permanent Generation.
So, what is the easiest way to create a memory leak in Java 8?
I think a common inner class memory leak would work. Example taken from the internet:
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...
}
}
What happens here is the createLeak() factory method return Leak class and theoretically LeakFactory object is eligible for GC to be removed as we don't keep reference to it. But the Leak class needs LeakFactory to exists thus LeakFactory will never be deleted. This should create a memory leak no matter what Java version you use.
链接地址: http://www.djcxy.com/p/92032.html上一篇: 在创建大量线程时.Net内存泄漏
下一篇: 在Java 8中创建内存泄漏