gpt4 book ai didi

java - 在 Java 8 中创建内存泄漏

转载 作者:行者123 更新时间:2023-12-02 05:50:52 25 4
gpt4 key购买 nike

同样的问题已再次得到回答( Creating a memory leak with 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 版本,这都会造成内存泄漏。

关于java - 在 Java 8 中创建内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23552912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com