I am aware that memory allocation is not explicitly required in Java, as the JVM handles allocation behind the scenes. Even though I am not required to allocate memory, for the sake of testing a memory greedy application, how would I be able to hold objects of certain numbers of bytes?
The current solution is to instantiate arrays of the primitive ‘byte’. If I want to hold 5 MB worth of objects, I create an array of bytes.
byte[] b = new byte[5000000];
Is there a better way to explicitly allocate memory in a Java JVM, if only for the sake creating / releasing objects of known size for some unit tests?
There isn’t really a better way of doing it. ‘new’ is the only way to explicitly occupy memory (except allocating stack by calling a method, for example).
is the most controllable way of doing it. It won’t allocate exactly 5000000 bytes, thanks to object overhead, but it’s pretty close.