Java automatically manages the heap and stack, and the programmer cannot directly set the heap and stack.

Operating system heap and stack:

Heap (operating system) : The heap is usually allocated and released by the programmer. If the programmer does not free it, it may be reclaimed by the OS at the end of the program, similar to a linked list.

Stack (operating system) : released automatically by the operating system, storing function parameter values, local variable values, etc. The operation is similar to that of stacks in data structures.

Why is the MEMORY of the JVM distributed in the operating system heap? Because the stack is the operating system of the operating system management, it will be recycled at any time, so if the JVM on the stack, the Java a null object is difficult to determine who will be recycled, the existence of the gc sense don’t have, but must achieve automatic release of stack also need to consider the JVM, so on the heap is the most appropriate.

** The figure above shows that ** THE JVM virtual machine resides in the operating system heap, and the programmer writes classes that are loaded into the virtual machine to execute: When A classLoder starts, the classLoader will live in the HEAP in the JVM. Then it will go to the host hard disk and load A.lass into the JVM’s method area. The byte file in the method area will be taken by the virtual machine and new A bytecode () will be generated in heap memory. And then the memory file A bytecode has two references one to A’s class object and one to the classLoader that loads itself

Java virtual machine life cycle: The declared period begins when a Java application starts its main function and the virtual machine is started at the same time. The Java virtual machine instance ends only when all non-daemons in the virtual machine instance end.

The relationship between the Java virtual machine and the main method: The main function is an entry point to a Java application. When the main function is executed, the Java virtual machine starts. Starting a few main functions starts several Java applications, as well as several Java virtual machines.

Java virtual machine has two kinds of threads, one is called daemons, and the other is called non-daemons (also called normal threads). The main function is a non-daemons, and the VIRTUAL machine gc is a daemons. In a Java virtual machine, instances of the Java virtual machine will not exit as long as any non-daemon thread has not terminated, so even if the non-daemon thread exits, the anonymous thread started in main is also a non-daemon thread, and it has not terminated, so the JVM cannot exit

The VIRTUAL machine’s GC is a typical daemon thread.

The JVM declaration cycle ends when all non-daemons have been declared:

public class MianAndThread{ public static void main( String args[]){ new Thread(new Runnable(){ @override public void run(){ Thread.currendThread.sleep(5000s); System.out.println(" Println after 5s sleep, this is a non-daemon thread outside main, this is out after this reference ends, the JVM declaration cycle ends. }} System.out.println(" Mian thread prints directly, mian thread ends, Java /javaw.exe process of computer task manager is not finished." )}}Copy the code

Instead of creating an empty variable and collecting it immediately, GC garbage collection is automatically collected when the variable is out of scope.

The original flow of the program in the JVM:

** First, when a program is started, its class is loaded by the classloader into the method area (Permanent), the execution engine reads the bytecode adaptive parsing of the method area, runs it as it parses (one way), and then the PC register points to the location of main. The virtual machine starts by reserving a stack frame for main in the Java stack (one for each method), and then runs main. The code in Main is mapped by the execution engine to the corresponding implementation in the local operating system, and then calls the local method interface. When the local method runs, The manipulation system assigns a local method stack to store temporary variables, then runs the local method, calls the operating system APIi, and so on. 支那

** According to the Java Virtual Machine specification, OutOfMemoryError is thrown if the memory space of the method area does not meet the memory allocation requirements. 支那

** JVM structure diagram: **

支那

支那

The figure above can be divided into “functional zones” and “data zones” (see 13.1 below). Functional zones: Garbage collection system, classloader, execution engine; Data area: that is, the entire runtime data area; 支那

JVM internal execution flow diagram:

Summary of the life cycle of each module in the JVM structure diagram:

** Starting a JVM application is starting a process. When booted, an area of JVM memory is created in the operating system’s heap. For each small module in Figure 13, the declaration cycle is **

Virtual machine stack, local method stack, program counter these three modules are thread private, there are as many threads as there are these three modules, the declaration cycle is the same as the owning thread declaration cycle. Take the program counter as an example, because multithreading is realized by the thread alternately switching and allocating execution time, so when the thread cuts back to the correct execution position, each thread has an independent program technology, the counters between each thread do not affect each other, independent storage.

The rest is consistent with the JVM virtual machine lifecycle.

The program counter module is the only part of the JVM memory region that does not report outofMemoryError.

We conclude that JVM memory consists of two subsystems and two components: the Classloader subsystem and the Executionengine subsystem; The two components are the Runtimedataarea(Runtimedataarea) component and the Nativeinterface(local library interface) component.

As you can see from the figure, the runtime data area consists of five parts: method area, heap, virtual machine stack, local method stack, and program counter

What are local library interfaces and local method libraries? (1) Local method library interfaces: the set of methods in the programming language used by the operating system, which are owned by the operating system. (2) The local method library is stored in the dynamic link library, that is. DLL (Windows system) file, the format is unique to each platform. (3) I feel that the local library interface is a bit redundant, take the following code as an example:

Computes the sum of two ints (passing int and returning int)

class Calc { static{ System.loadLibrary("Calc"); } public static native int add(int a, int b); Public static void main(String[] args) {system.out.println (add(11,23)); }}Copy the code

Corresponding C code:

JNIEXPORT jint JNICALL Java_Calc_add(JNIEnv *env) #include <stdio.h> #include "calc.h" jclass jc, jint a, jint b) { jint ret = a + b; return ret; }Copy the code

In Java code, c libraries (native method libraries) are loaded via System.loadLibrary(“”) to interact directly with the operating System platform.

Parent delegation: The JVM uses parent delegation by default when loading classes. Generally speaking, when a specific class loader receives a request to load a class, it first delegates the loading task to the parent class loader and recurses in turn. If the parent class loader can complete the class loading task, it returns successfully. Only if the parent class loader is unable to complete the load task, do the load itself.

For example, when the JVM loads test. class,

(1) The custom loader is first checked to see if it has been loaded, and if it has been loaded, the bytecode is returned.

(2) If the custom loader has not been loaded, ask the previous loader (i.e. AppClassLoader) whether the test.class has been loaded.

(3) If the ExtClassLoader has not been loaded, it will ask whether the previous layer (ExtClassLoader) has been loaded.

(4) If no, continue to ask whether the previous layer (BoopStrap ClassLoader) has been loaded. If the BoopStrap ClassLoader has not been loaded, go to the specified class loading path (“sun.boot.class.path”) and check whether the test. class bytecode exists. The next layer loader is not known to go to the specified class loading path (java.ext.dirs).

(6) and so on, finally to the path specified by the custom class loader has not yet

The code is as follows:

protected Class<? > loadClass(String name, Boolean resolve) throws ClassNotFoundException {synchronized (getClassLoadingLock(name)) {// First check if Class<? > c = findLoadedClass(name); if (c == null) { long t0 = System.nanoTime(); try { if (parent ! LoadClass c = parent.loadClass(name, false); } else {// If the parent loader is empty, call Bootstrap Classloader c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. long t1 = System.nanoTime(); Findclass c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); ResolveClass (c); resolveClass(c); } return c; }}Copy the code

Why use this type of loading? A couple of things to note here: 1, the class loader code itself is also a Java class, so the class loader itself has to be loaded, so obviously there has to be a first class loader that is not a Java class. This is bootStrap, written in c++ and this is Java. 2. Although bootStrap, extclassLoader, and AppClassLoader are parent-child class loaders, they use a combinative relationship instead of inheritance. 3, advantages, with a hierarchical relationship with priority, the more basic classes, the more the upper class loader to load, can be more generally said that several JAR packages like JDK must be in the top, and then we reference the package, and finally we write our own, to ensure the stability of Java programs.

JDK(Java Development Kit) is a software Development Kit (SDK) of the Java language. In the JDK installation directory, there is a JRE directory. There are two folders: bin and lib. Bin is the JVM, and lib is the library that the JVM needs to work.

JDK, JRE, AND JVM:

The JVM runs a simple procedure:

Java files are compiled into a.class file. For example, if you need maven to install a jar file, the jar package contains.calss files. These steps are done on Eclipse. Then the classloader, all the way up to the interpreter, belongs to the JVM

Explain the contents of each module of the JVM structure diagram:

Program Counter Register: Also known as the PC Register, is a small memory space that can be seen as a line number indicator of the bytecode being executed by the current thread. In the conceptual model of virtual machine, bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to be executed, branch, loop, jump, exception handling, thread recovery and other basic functions need to be completed by this counter. (1) Different from the PC register of computer hardware the two are not slightly different. The computer uses the PC register to store “pseudo-instructions” or addresses. Compared with the VIRTUAL machine, the PC register is represented as a piece of memory (a word long, the virtual machine requires the minimum word length of 32 bits). The function of the VIRTUAL machine’S PC register is also to store pseudo-instructions, more specifically, to store the address of the instruction to be executed. (2) When the vm is executing a native method, the JVM’s PC register stores undefined. (3) The program counter is thread private and has the same lifetime as the thread, with one for each thread. (4) This memory region is the only one that does not have any OutOfMemoryError cases specified in the Java Virtual Machine specification.

Java Virtual Machine Stack (Java Virtual Machine Stack) :(1) a thread is private. Its life cycle is the same as that of a thread. Each thread has one. (2) A JVM stack is created for each thread. Each stack frame in the JVM stack holds variables of the local basic types in the current thread. The JVM stack holds only one address on the heap for non-basic types of objects, depending on the return of reference and partial results. (3) The process of each method from being called to the completion of execution corresponds to the process of a stack frame in the virtual machine stack from being pushed to being pushed out. (5) Stack operation principle: Are based on the data Stack Frame (Stack Frame) format exists, the Stack Frame is A memory block, is A set of data, is A data set of data related to methods and operating period, when A method is invoked A creates A Stack Frame F1, and pinned to the Stack, A method is called again B method, generating the Stack Frame press F2 were into the Stack, Method B calls method C, so frame F3 is pushed… After the operations are complete,…… is displayed F3 stack frame, F2 stack frame, F1 stack frame. (6) The minimum unit of JAVA virtual machine stack can be understood as a stack frame, a method corresponds to a stack frame, a stack frame can execute many instructions

To illustrate the dynamic link above, for example, when the main method calls method1(), the operation instruction will trigger the dynamic link and call method1() in the method area, and then push method1() onto the virtual machine stack to execute the instructions for the stack frame. In addition, if the code represented by the instruction is a constant, this is also a dynamic link, which will also find data from the runtime constant pool in the method area that was used to store variables when the class was loaded.

Native Method Stack:

(1) First explain what is a native method: a native method in the JVM refers to a class of methods whose modifiers are native but whose body is not written in Java code. The significance of this class of methods is of course proposed to fill the defects of Java code that is not convenient to implement. The case will be introduced in detail in the following 22 points.

(2) The function is similar to that of Java virtual machine stack, but the difference is that the virtual machine stack serves the Execution of Java methods for virtual machines, while the local method stack serves the Native methods used by virtual machines.

(3) is thread private, its life cycle is the same as threads, each thread has one.

Java Heap:

(1) Is the largest chunk of memory managed by the Java VIRTUAL machine.

(2) Unlike the above three, the heap is shared by all threads of the JVM.

(3) Created when the VM is started.

(4) The only purpose is to store object instances, almost all object instances and arrays have to allocate memory here.

(5) The Java heap is the primary area managed by the garbage collector.

(6) As a result, the Java Heap is often referred to as the Garbage Collected Heap. From the point of view of memory collection, the Java heap can also be subdivided into: new generation and old generation; The new generation can be divided into Eden space, From Survivor space and To Survivor space. (23 points)

(7) The Java heap is discontinuous, logically continuous, and resizable on computer physical storage (controlled by -xMS and -XMX).

(8) OutOfMemoryError will be raised if there is no memory in the heap to complete the allocation of instances and the heap can no longer be extended.

Method Area:

(1) Created when the VM starts.

(2) Shared by all JVM threads.

(3) In addition to the fact that the heap does not require discontinuous memory space and can be fixed size or scalable, you can also choose not to implement garbage collection.

(4) It is used to store data such as class information loaded by virtual machine, constant, static variable, and machine instruction set in binary form realized by compiled method.

(5) Information about the loaded class is stored in Methodarea memory. When the virtual machine loads a type, it uses the class loader to locate the corresponding class file, then reads the class file contents and transfers them to the virtual machine.

(6) The Runtime Constant Pool is part of the method area. The Constant Pool Table is used to store various literals and symbolic references generated at compile time. This part of the Constant Table is stored in the runtime Constant Pool after the Class is loaded into the method area.

Instruction sets are an important concept because programmers write code that is translated into instruction sets in the JVM.

Take a look at the positions in figure 13 above: The code foo on the left is the instruction set, which is visible in the methods area, not to speak of the program counter. The local variable area is located in the virtual machine stack. The evaluation stack (operand stack) at the bottom right is also located in the Java virtual machine stack as we can clearly see from the animation.

In addition, in the figure, instructions are JVM instructions after Java code is compiled by JavAC, the PC register points to the address of the next instruction to be executed, the local variable area stores the local variables generated during function execution, and the stack stores the intermediate and final results of calculation.

The source code for the above execution is:

public class Demo { public static void foo() { int a = 1; int b = 2; int c = (a + b) * 5; }}Copy the code

First, constant 1 is pushed, the top element is 1, and then the top element is moved to the local variable area. Constant 2 is pushed, and the top element is changed to 2, and then the top element is moved to the local variable area. 1, 2, in turn, then into the stack again, pop up the top two elements combined results into the stack, 5 into the stack, the top two elements popup and multiply the result into the stack, then the stack into 15, finally moved into a local variable. If there is no stack frame in the stack corresponding to the current thread, the Java stack will also be destroyed by the JVM.

The class loader subsystem :(1) loads the contents of the class file to the methodarea within the Runtimedataarea based on the given fully qualified name class name (e.g. Java.lang.object). Java programmers can write their own classLoaders using the extends java.lang.ClassLoader class. (2) The loading process of (1) is as follows: When A classloader starts, the classloader lives in the JVM heap. It then goes to the host hard disk and loads A.lass into the JVM’s MethodArea. This memory file has two references, one to A’s class object and one to the classloader that loads itself.

Executionengine subsystem: (1) Is responsible for executing the instruction set from the class loader subsystem which is loaded in the method area contained in the class. In plain English, the class loader subsystem loads the code logic (when to if, when to add, subtract) into the method area in the form of instructions. The execution engine is responsible for executing these instructions.

(1) The main execution process of the program in THE JVM is the continuous interaction between the execution engine and the runtime data area, which can be understood as the “GIF in the method area” above.

(2) But the instructions in the method area are still human-readable, and the execution engine’s job is to translate the instructions into the JVM’s execution language (also known as the language of the operating system), which in turn translates into computer machine code.

(3)

Interpreter: Reads, interprets, and executes bytecode instructions one by one. Because it interprets and executes instructions one by one, it can interpret bytecode quickly, but execute it slowly. This is a disadvantage of languages that explain execution. Bytecode is a “language” that basically interprets execution. Just-in-time (Just – In – Time)

Compilers: Just-in-time compilers were introduced to compensate for the shortcomings of the interpreter. The execution engine first executes as interpreted, and then, when appropriate, the just-in-time compiler compiles the entire bytecode into native code. Then, the execution engine no longer has to interpret the execution method, it can execute it directly from native code. Executing native code is much faster than interpreting it line by line. Compiled code can execute quickly because native code is stored in the cache.

The bytecode interpreter is the same as the bytecode interpreter in 20. Jit simply means that code becomes “hot code” when some method is reused more often than a certain value. This hot code is then compiled into local code (aka cache) to speed up access.

Native methods:

(1) A native method is a method with a native identifier modifier;

(2) Native modifiers do not provide a method body, but because their implementation body is externally implemented by non-Java code, they cannot be used with abstract.

(3) The meaning of existence: the code that is not convenient to write in Java language is more appropriate to write in a more professional language; There are even JVM implementations that are written in C, so they can only be written in C

(4) More native methods are preferably compatible with the interpreter language of the JDK’s execution engine (execution engine, interpreter: see execution engine 21);

(5) Most of the core codes of Windows, Linux, UNIX and Dos operating systems are written in C and C++, and the underlying interfaces are written in assembly.

(6) Why is the PC program counter undefined? Read all the above points can be easy to understand their own. At the beginning of class loading, the native modified method is stored in the local method stack. When the native method needs to be called, it calls an address pointing to a method in the local method stack, and then executes the method to interact directly with the operating system and return the running result. The whole process does not go through the execution engine’s interpreter to interpret the bytecode into the operating system language, and the PC counter does not come into play.

GC garbage collection mechanism:

Learn about heap memory:

After the class loader reads the class file, it needs to put the class, method and constant variables into the heap memory to facilitate the execution of the executor. The heap memory is divided into three parts:

1) new area

Spawns are areas where classes are born, grow, and die, where a class is created, applied, and finally collected by the garbage collector to end its life. The freshman area is divided into two parts: Eden Space and Survivor Pace, where all classes are newly created. There are two Survivor zones: Survivor 0 space and Survivor 1 space. When Eden runs out of space, the program needs to create objects again, and the JVM’s garbage collector will perform a Minor GC on Eden, moving the remaining objects in Eden to survivable zone 0. If the surviving zone 0 is also full, then the zone is recycled and moved to zone 1. What if one goes to the top? Then move to the retirement area. If the endowment area is also full, a Major GC (FullGCC) will be generated to clean up the endowment area. If the endowment area fails to save objects after Full GC is performed, an OOM OutOfMemoryError will be generated.

If there is a Java. Lang. OutOfMemoryError: Java heap space is unusual, the Java virtual machine heap memory is not enough. There are two reasons:

A. Java The heap memory setting of the VM is insufficient. You can use -xms and -xmx to change the heap memory setting.

B. A large number of large objects are created in the code and cannot be collected by the garbage collector for a long time (there are references).

(2) pension area

The endowment area is used to hold JAVA objects filtered from the newborn area, where the general pool objects are active. The permanent storage area is a permanent memory area, used to store the JDK’s own Class,Interface metadata, that is, it stores the runtime environment necessary Class information, is not loaded into the garbage collector data. Shutting down the JVM will free up memory for this area.

(3) permanent area

The permanent storage area is a resident area of memory used to store metadata about classes and interfaces carried by the JDK itself. That is, it stores information about classes that are necessary for the runtime environment. Data loaded into this area is not collected by the garbage collector.

If there is a Java. Lang. OutOfMemoryError: PermGen space, that is a Java virtual machine for permanent generation Perm enough memory Settings. There are two reasons:

A. A large number of third-party JAR packages need to be loaded to start the program. For example, too many applications are deployed in one Tomcat.

B. A large number of classes generated by dynamic reflection are continuously loaded, eventually leading to the full Perm area.

Description:

Jdk1.6 and before: Constant pool allocation in persistent generation.

Jdk1.7: yes, but has gradually “gone permanent generation”.

Jdk1.8 and after: no (Java. Lang. OutOfMemoryError: PermGen space, this kind of mistake will not appear in Jdk1.8).

24, runtime data area modules collaborative work summary of good figure (from: blog.csdn.net/wangtaomtk/…

The first code to execute is:

When calling another method:

The process of compiling Java code from a.java file to a.class file.

Note: The source code is a. Java file and the JVM bytecode is a. Class file

Load the bytecode file or execute the main method first: load the bytecode file into the method area, and then find the main executable.

Java is compiled into a class file. How does the JVM find this file from the hard disk and load it into the JVM?

The Java native Interface (JNI) finds the class file, loads it into the JVM, finds the main method, and executes it.

The eight basic types we usually refer to are stored in the stack: runtime data area — “virtual machine stack –” a stack frame of virtual machine stack — “local variable table in the stack frame; In addition to the eight basic types of data stored in the local variable table, it can also store the size of the minimum unit variable slot of the capacity of a local variable table, which is usually represented as reference. So you can put strings, but with String A =”aa”; If it is a new Object(), it must be stored in the stack, which stores the address of the stack execution heap.

The heap size -xms-xmx is set to the same, because larger -xmx means more tomcat memory is available, which means that the JVM calls garbage collection less often (which is invoked automatically when the JVM runs out of memory) and avoids the need for the JVM to reallocate memory after each garbage collection.

It is up to the system to decide when the GC will be executed and it is not predictable.

Method areas are also called persistent generations in heap memory, as shown in the following example:

Student s = new Student("小 小 ", 18); S is a pointer, stored on the stack. New Student(" Xiaoming ", 18) is the object stored in the heap. Information for the Student class is stored in the methods area. Summary: Instances of objects are stored on the heap, object metadata (instantKlass) is stored in the method area, and references to objects are stored on the stack.Copy the code

Class loading is based on whether the method area has already loaded the class, so the class in the method area is unique. The classes in the method area are run-time, in-use, and not GC, so they can be understood as permanent generations.

Java memory model

** Read so much above the last knowledge point, understand a little knowledge of multi-threading. We should know that the virtual machine stack, PC registers, and local method stack are owned by each thread in the data memory area at runtime. Obviously, these are independent of each other and there is no thread unsafe problem. But what about the thread unsafe, locking, and so on? 支那

In fact, the thread unsafe problem is caused by the CPU, see the following figure, a simple understanding of CPU **

支那

支那

** Inside the CPU there is a set of CPU registers, which are the CPU’s memory. The CPU can manipulate registers much faster than the computer’s main memory. There is also a CPU cache between main memory and THE CPU registers, and the CPU operates on the CPU cache faster than main memory but slower than the CPU registers. Some cpus may have multiple cache layers (level 1 and level 2). A computer’s main memory, also known as RAM, is accessible to all cpus and is much larger than the caches and registers mentioned above. When a CPU needs to access main memory, it first reads some of the main memory data into the CPU cache, and then the CPU cache into the register. When the CPU writes data to main memory, it also flushes registers to the CPU cache and then, on some nodes, flushes the cached data to main memory. 支那

Bridging between the Java Memory model and hardware architecture As mentioned above, the Java memory model and hardware memory architecture are not consistent. There is no distinction between stack and heap in the hardware memory architecture. From the point of view of hardware, most of the data, whether stack or heap, will be stored in main memory, of course, some of the stack and heap data may be stored in CPU registers, as shown in the following figure, Java memory model and computer hardware memory architecture is an intersection:

支那

支那

When objects and variables are stored in various memory areas of the computer, there are bound to be some problems, of which the two main problems are:

  1. Visibility of shared objects to various threads 2. Contention of shared objects

Question 1:

Visibility of a shared object When multiple threads operate the same shared object simultaneously, if the volatile and synchronization keywords are not used properly, the update of a shared object by one thread may make the shared object invisible to other threads.

Imagine that our shared object is stored in main memory. A thread in a CPU reads main memory data into the CPU cache and then makes changes to the shared object, but the changed object in the CPU cache has not been flushed into main memory, so changes made by one thread to the shared object are not visible to threads in other cpus. The end result is that each thread ends up copying the shared object, and the copied object resides in a different CPU cache.

The following figure shows the process described above. The thread running on the left CPU copies the shared object obj from main memory into its CPU cache, changing the count variable of object obj to 2. But this change is not visible to the thread running on the right CPU because the change has not been flushed into main memory:

To solve the problem of shared object visibility, we can use the Java volatile keyword. Java’s volatile keyword. Volatile ensures that variables are read directly from main memory, and that updates to variables are written directly to main memory. The volatile principle is based on CPU memory barrier instructions.

Question 2:

Contention occurs if multiple threads share an object, and if they modify the shared object simultaneously. As shown in the figure below, thread A and thread B share an object, obj. Let’s say thread A reads the obj. count variable from main memory into its CPU cache, and thread B also reads the obj. count variable into its CPU cache, and both threads increment obj. count. At this point, the obj. count + 1 operation is executed twice, but in different CPU caches.

If the increments are sequential, the obj. count variable will add 2 to the original value, and eventually obj. count in main memory will have a value of 3. In the following figure, however, the two increment operations are parallel. Either thread A or thread B flush the results into main memory first. Eventually, the obj. count increment in main memory only increases once to 2, even though there are two increment operations.

To solve this problem, use Java synchronized blocks. Synchronized blocks guarantee that only one thread can enter the contention area at a time. Synchronized blocks also guarantee that all variables in the block will be read from main memory. Updates to all variables are flushed into main memory when a thread exits the block. It does not matter whether these variables are volatile or not.

Volatile essentially tells the JVM that the current value of a variable in its register (working memory) is indeterminate and needs to be read from main memory; Synchronized locks the current variable so that only the current thread can access it and other threads are blocked.

Volatile can only be used at the variable level; Synchronized can use volatile at the variable, method, and class levels only to achieve variable change visibility, not atomicity; Synchronized can guarantee the change visibility and atomicity of variables

Volatile does not block threads; Synchronized can cause threads to block. Volatile variables are not optimized by the compiler; Variables marked with synchronized can be optimized by the compiler to support the underlying principles of the Java memory model

Difference between method area and heap

The method area holds the information of the class, including static variables of the class, final type variables, field automatic information, method information, and the instruction set for processing logic. If we think about it, that’s all there is ina class. The heap contains objects and arrays.

1, this is related to the object we usually say is an instance of a class, is it a bit of a tumble? Class, and the corresponding relation of here is “methods” “heap – object”, “people”, for example, pile is put inside you that this “real people, of flesh and blood”, the area method is described in your text messages, such as “your name, height, weight, and your behavior, such as eating, walking, such as”.

2. Another way to think about it is that we learned previously that classes in a method section are unique and synchronized. But we tend to have the same class new several times in our code, so we have multiple instances, and since we have multiple instances, we allocate multiple instance space memory in the heap.

Does the content of the method area load all the class information of a project at once and then execute it or does it execute while loading it?

In fact, from the performance perspective, you can also guess that only the currently used class is loaded, that is, execute as you load. For example, when we start a Spring project using Tomcat, the database information, interceptor information in the configuration file, service annotation information, some validation information, etc., will be loaded first in the method area. However, if we want the program to start faster, we will set lazy loading, remove some validation, such as some class information to load when it is actually used, so that the content of the method area can be loaded first, or can be loaded when it is used.

Method area, stack, heap between the process

The information of the class loaded by the class loader is put into the method area. After executing the program, the methods in the method area are pushed like the top of the stack. (Here the stack has the address of this object in the heap.)