To mask differences in memory access between hardware and operating systems, the JVM has developed a JMM memory model to enable the same Set of Java programs to perform the same performance on different platforms. This is the effect of a compilation running cross-platform everywhere.

JVM memory allocation concepts

Two important concepts of the JVM: Heap and Stack

In Java, the Heap is an area of run-time data, which is responsible for by the garbage collector. It has the advantage of allocating memory dynamically. The life cycle does not have to be told to the compiler in advance. The downside: Since memory is allocated at run time, access is relatively slow.

The Stack in Java is faster than the Heap, second only to the register, and the data in the Stack can be shared. However, the disadvantage of the stack is that the life cycle is determined in the compiler, which lacks flexibility and mainly puts some basic types of variables.

The JMM requires that the call Stack and local variables (local variables) be placed on the Stack and objects on the Heap. A local variable can refer to an object that is placed on the Heap. A class may have methods in which local variables are placed on the thread stack, even if the objects to which those methods belong are still on the Heap. An object’s member variables may be placed on the Heap along with the object, regardless of whether the member variable is a primitive or a reference type. Static member variables are placed on the Heap along with the class definition. Objects stored on the heap can be accessed by the thread that holds the object.

When a thread can access an object, it can access the object’s member variables. If two threads call the same method on an object at the same time, they will both access the object’s member variables, but each thread has a private copy of that member variable.