0

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?

Community
  • 1
  • 1
Alex
  • 83
  • 1
  • 11
  • I don't know why the question you linked to survived and got so many upvotes - it doesn't appear to be on topic for this site. – Floris May 08 '14 at 21:35
  • 1
    @Floris What is and is not "on topic" for StackOverflow has evolved over the years. That question was posted 3 years ago, when SO questions and answers were allowed to be much broader. – Mike Clark May 08 '14 at 21:42
  • @mikeclark - I figured it was something like that. Thanks for the "historical" perspective; I've only been here a little over a year... – Floris May 08 '14 at 21:47
  • What makes you think that those perm gen leaks are not leaks any more? The problem is only delayed until your OS starts swapping and your system goes slow. Not necessarily an improvement over an exception. – Rafael Winterhalter May 08 '14 at 22:18
  • The answer to your linked question is misleading in implying that a memory leak must involve the PermGen. Memory leaks can happen on the heap as well, with quite obvious code, and Java 8 hasn't changed anything in that respect. – Marko Topolnik May 09 '14 at 08:21

1 Answers1

2

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.

kazuar
  • 1,094
  • 1
  • 12
  • 14