“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
The definition of the heap
Objects created with the new keyword use heap memory.
concept
For Java applications, the heap is the largest chunk of memory managed by the JVM. Is an area shared by all threads and created when the virtual machine is started. The sole purpose of this area is to hold object instances, and “almost” all object instances in Java programs are created and allocated memory here.
The JVM specification describes the heap as “all object instances and arrays should be allocated on the heap.”
The JVM specification states that the heap can be physically discontiguous, but logically it should be treated as contiguous, just as we use disk space to store files without requiring each file to be contiguous.
The heap can be implemented as either fixed size or extensible, but most current Java virtual machines are implemented as extensible (with the -xmx and -xMS parameters). The JVM throws an OutOfMemoryError if there are no completed instances of memory allocated in the heap and cannot be extended.
The characteristics of
1. It is shared by threads, so all objects in the heap need to consider thread safety. Garbage collection mechanism 3. Overflow of memory
Heap overflow
Although there is a garbage collection mechanism, objects are released as garbage collection when they are no longer in use.
However, when objects are created and still in use, they are not garbage collected. When the number of objects reaches a certain level, the heap memory will be exhausted, resulting in the heap overflow problem.
example
public static void main(String[] args){
int i = 0;
try{
List<String> stringList = new ArrayList<>();
String a = "hello";
while(true){ stringList.add(a); a = a + a; i++; }}catch(Throwable a){ e.printStackTrace(); Sytem.out.println(i); }}Copy the code
When running this example I set the heap to 8-XMx8M to make it faster for the JVM to throw overflow messages.
Running the above example throws an out-of-memory message: Front of Java. Lang. OutOfMemoryError: Java heap space is out of memory error, behind the Java heap space is Java heap space, the translation is the locating information is specific heap memory overflow.
This is an example where the object is constantly being referenced and information is being inserted so that the stringList size exceeds the size of the heap memory.