Does Java throw an exception before it really exits memory?

I want to create a large int array that almost fills all the memory available to the JVM. Take this code, for example:

    final int numBuffers = (int) ((runtime.freeMemory() - 200000L) / (BUFFER_SIZE));
    System.out.println(runtime.freeMemory());
    System.out.println(numBuffers*(BUFFER_SIZE/4)*4);
    buffers = new int[numBuffers*(BUFFER_SIZE / 4)];

When launched with a heap size of 10M, this throws an OutOfMemoryException, despite the output from printlns:

9487176
9273344

I understand that the array will have some overhead, but not 200k, of course? Why can't Java allocate memory for what it claims to have enough space? I have to set this constant, which is subtracted by something around 4M, before Java starts it (by the time printlns look more similar: 9487176 5472256)

Even more confusing if I replace the buffers with a 2D array:

buffers = new int[numBuffers][BUFFER_SIZE / 4];

200k, , - ( 2D- , 1D-, ).

?

+5
3

( ), .

, JRE. 200k , 10M .

, 32- - 12 IIRC ( , , , AFAIK 8 ). - 19 .

, Java 2D () , .

+5

2D- , . , . , - , , - , .

+1

JVM .

, 10 x long:

xxxxxxxxxx 

0 somehere. :

xxxxxxx0xx

10 x . 8 x s, , 9 x s.

, , .

. , . , Java , , . , .

There are also many other factors that you should consider, some of which include: memory leaks either in a virtual machine (not very) or on your application (also unlikely for a simple scenario), unreliability of use Runtime.freeMemory()(GC may work immediately after a call, and available free memory may change), implementation details of each specific JVM, etc.

The fact is that, as a rule, it is not always expected that everything will be available for your application Runtime.freeMemory().

0
source

All Articles