0
votes

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?

1
I don't understand the question... new is not good? - Tudor
Is it for JNI stuff? If so, allocating a DirectByteBuffer will definitely allocate your memory then & there. - EdH
@Ed H., This is not for JNI. Missed the 'new', edited post. - Noah
What would make something a "better way"? Or, what's bad about what you're doing now? Offhand, I can't think of anything better. - Ed Staub
Creating an object seemed hackish, I was hoping for more direct control. True, in C I would have no problem with this, but the app is in java and this is a corner case I need to write some blocks for, not a huge architectural change. - Noah

1 Answers

0
votes

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

byte b = new byte[MEM_SIZE];

is the most controllable way of doing it. It won't allocate exactly 5000000 bytes, thanks to object overhead, but it's pretty close.