简体   繁体   English

消耗JVM内存

[英]Chew up JVM memory

I am testing an application that monitors the health of an application and one of the determining factors is the jvm memory. 我正在测试一个监视应用程序运行状况的应用程序,而决定因素之一就是jvm内存。 I am curious as to how I can eat this up so I reach the threshold for testing? 我很好奇如何吃完才能达到测试的门槛? Would this work? 这行得通吗?

ArrayList<Object> list = new ArrayList<Object>();
while(true){
    list.add(new Object());
}

similar to chewing through application memory in C where I am constantly malloc'ing things? 类似于在我不断分配内存的C中仔细检查应用程序内存? Or will the garbage collector come and clean all this up for me? 还是垃圾收集器会来帮我清理所有这些? Or have I missed the mark entirely? 还是我完全错过了标记?

No, you haven't missed the mark. 不,您没有错过分数。 The garbage collector will only collect objects that you no longer have a reference to. 垃圾收集器将仅收集您不再引用的对象。 In your sample code, the list will always be in scope, as will all the objects it references so you will eventually fill up the heap and generate an OutOfMemoryException. 在示例代码中,列表将始终在范围内,列表所引用的所有对象也将始终在范围内,因此您最终将填充堆并生成OutOfMemoryException。

As has been said in the comments, using a plain Object is probably not the best way to do this depending on how big your heap is. 如评论中所述,根据堆的大小,使用普通对象可能不是实现此目的的最佳方法。 Larger objects or simple arrays of primitives will make your life easier. 较大的对象或简单的基元数组将使您的生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM