简体   繁体   中英

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. 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? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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