veltaandrg / JavaExercises

0 stars 0 forks source link

Array sizes and OutOfMemoryError #5

Open RodionGork opened 9 years ago

RodionGork commented 9 years ago

The following code tries to create arrays of different sizes. Size is gradually incremented so sooner or later the code will halt because the memory is exhausted. We then try to clear the memory and print out how large array was failed to create.

    byte[] array;
    int size = 3;
    try {
        while (true) {
            array = null;
            System.gc(); // this hints the JVM that memory could be cleared
            size *= 3;
            array = new byte[size];
        }
    } catch (OutOfMemoryError e) {
        array = null;
        System.gc();
    }
    System.out.println((size / 1000000) + " millions");

Try to execute this limiting the heap memory of java machine, i.e. run it (after compilation) as

java -Xmx100M OutOfMem

To give it only 100 Megabytes of memory. Which array size will be printed?

Then try to give it 1 Gigabyte (i.e. -Xmx1000M). How the maximal size have changed?

Now change array type from byte to short, then to long and at last to float. Repeat these experiments (do not forget to recompile the code). Collect the results in the form of table. Also write how much memory (in bytes) is required for array data themselves in each case.