Disclaimer: in this question we will use Java's exception throwing mechanism to probe the size of the runtime heap. As in question 7e2a, this is simply so that you can get some feeling for how the Java runtime works, and to show you more examples of how exceptions work. Again, it would be very bad practice to write a real application that deliberately uses up all available heap memory!
At runtime, the Java Virtual Machine reserves a certain amount of memory for the program heap, where objects live. Each time a new object is created, some memory is allocated on the heap. When an object becomes unreachable, the JVM's garbage collector will, in due course, free the associated memory.
If you create a very large number of objects, and if these objects remain reachable, you can exhaust the heap memory. In this case the
JVM will throw an OutOfMemoryError
. OutOfMemoryError
is another subclass of the abstract VirtualMachineError
class.
Write a program that uses an infinite loop to create Integer
objects in such a way that they are never garbage-collected.
Intercept the OutOfMemoryError
that will eventually be thrown, and print the number of Integer
objects that were
created before heap memory was exhausted.