Java Memory Model

What is a JVM ?

Java Virtual Machine | Various Components of Java Virtual Machine
  • JVM – Java Virtual Machine
  • It is an abstract machine.
  • It is a specification that provides runtime environment in which java bytecode can be executed.
  • JVMs are available for many hardware and software platforms
  • However JVM is platform dependent.
  • Whenever we execute a Java program, a separate memory area is reserved for storing various parts of our application code which we roughly call JVM memory.
  • Without having a good understanding of how JVM actually consumes the memory and how garbage collector uses different parts of this volatile memory, we may miss some important considerations for better memory management, thus better performance.

It is:

  1. A specification 
    • where working of Java Virtual Machine is specified.
    • But implementation provider is independent to choose the algorithm.
  2. An implementation 
    • Its implementation is known as JRE (Java Runtime Environment).
  3. Runtime Instance 
    • Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

JVM,

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment
JVM | Java Virtual Machine - Javatpoint

 What is Java Garbage collection ?

  •  Garbage collection is the mechanism used in Java to de-allocate unused memory.
  • In java, garbage means referenced objects.
  • Java applications obtain objects in memory as needed.
  • It is the task of garbage collection (GC) in the Java virtual machine (JVM) to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses.

What is a Memory Model?

  • The memory model describes possible behaviors of a program.
  • It describes thread interaction with memory.
  • It Changes in the ordering of reads and writes can cause race conditions. 
  • This memory model provides sequential consistency for data race free programs

What is Java Memory Model?

  • Java Memory Model is the model that describes the behavior of memory in Java program.
  • It is a set of rules all JVMs have to follow to ensure correct working of our concurrent programs. 
  • it is specification which guarantees visibility of fields when you have reordered of instructions.

The java memory model specification specifies how and when a thread can see the value of a shared variable modified by another thread and how to access the shared variable when necessary

eg:

If you run the program in one JVM then you pick that program and pick it into another JVM, the program output is exactly the same.

Java Memory Model Structure

  • The Java Virtual Machine defines various run-time data areas that are used during execution of a program.
Java Memory Management - GeeksforGeeks