The Java Virtual machine memory model is the basis for running Java programs.
The Java Virtual machine divides its memory data into program counters, virtual machine stacks, local method Stacks, Java heaps, and method areas.
If we can define several of these areas according to the different access permissions, there are two categories: thread sharing and thread private. Thread sharing refers to a class of memory areas that can be shared by all threads, including the heap memory area, the method area, and the three memory areas of the run-time pool.
A simple sentence describes the purpose, the program counter is used to hold the next running instruction, the virtual machine stack and the local method stack to hold the function call stack information, the Java heap is used to hold the Java program to run the object and other data, the method area is used to store the program's class metadata information.
1. Program counter
When the number of threads exceeds the number of CPUs, CPU resources are automatically robbed between threads based on the time slice polling method. For a single-core CPU, only one thread can be running at a time, and the other threads must be switched out until the polling wheel is able to use the CPU resources, so each thread must use a separate program counter that is used to record the next computer instruction that needs to be executed. For multi-core CPUs, multiple threads can be allowed to work simultaneously, the counters between the various threads do not affect each other, working independently, so the program counter is a thread-unique piece of memory space. In order for the thread to switch back to the correct execution location, each thread must have a separate program counter.
2. Virtual Machine stack
The region is located in general-purpose ram, with the so-called "stack pointer" allowing us to access the processor, which is second only to registers.
Example of a virtual machine stack code:
1 ImportJava.util.concurrent.CountDownLatch;2 Public classTestjvmstack {3 Private intCount = 0;4 Public voidrecursion () {5Count + +;//stack depth plus 16 7Recursion ();//recursive consumption stack memory allocation8 }9 Public voidTeststack () {Ten One Try { A recursion (); -}Catch(Java.lang.StackOverflowError e) { -System.out.println ("Print out the depth of stack overflow:" +count); the e.printstacktrace (); - } - } - Public Static voidMain (string[] args) { +Testjvmstack ts =NewTestjvmstack (); - Ts.teststack (); + } A}
Operation Result:
1 print out the stack Overflow depth: 186642java.lang.StackOverflowError3at Testjvmstack.recursion (Testjvmstack.java:8)4at testjvmstack.recursion (Testjvmstack.java : 8)5at testjvmstack.recursion (testjvmstack.java:8)6 at Testjvmstack.recursion (Testjvmstack.java:8)
3. Local Method Stack
Java Virtual machine memory model