0

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?

j-money
  • 509
  • 2
  • 9
  • 32
  • 2
    Maybe you can give [this](https://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java) a try – soufrk Jun 27 '18 at 12:50
  • In theory, a failure is not guaranteed, but in practice, this is sufficient to eat up all memory, but it may take a long time as a single object is quiet small. If you have a heap several GiBs large, you may encounter the problem that the `ArrayList` can’t hold more than 2³¹ objects. But just replacing `new Object()` with, e.g. `new int[10000]` may solve both problems. – Holger Jun 27 '18 at 13:32

1 Answers1

1

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.

Speakjava
  • 3,177
  • 13
  • 15