如何模拟 OutOfMemoryError: Metaspace

我想知道如何自己导致 OutOfMemoryError: Metaspace 异常?是否可以加载很多类并让它们在内存中停留很长时间。


斯蒂芬大帝
浏览 109回答 3
3回答

噜噜哒

要创建OutOfMemoryError: Metaspace使用javassist.ClassPool库。下面的示例将创建Metaspace错误。import javassist.ClassPool;public class OutOfMemoryErrorMetaspace {&nbsp; &nbsp; //ClassPool objects hold all the CtClasses.&nbsp; &nbsp; static ClassPool classPool = ClassPool.getDefault();&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int i = 0; i < 1000000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //makeClass method - Creates a new class (or interface) from the given class file.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class clas = classPool.makeClass(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i + " outofmemory.OutOfMemoryErrorMetaspace ").toClass();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Print name of class loaded&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(clas.getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java