JVM from entry to proficiency (super detailed summary of all JVM knowledge points, including interview questions)

table of Contents

JVM memory structure

Stack

heap

Garbage collection

Method of judging the death of an object

Garbage collection algorithm

Garbage collector

Synchronized keywords

Synchronized principle

Lock upgrade

Bias lock

Lightweight lock

Interview answer: Synchronized lock upgrade idea 1:


JVM memory structure

The JVM memory space is divided into five parts, namely: method area, heap, Java virtual machine stack, local method stack, and program counter.

Shared threads: method area, heap

Thread private: virtual machine stack, local method stack, program counter

Method area: constants, static variables, class information, runtime constant pool (literal, symbolic reference) .

The heap mainly stores arrays, class instance objects, string constant pools, etc.

The stack stores variables , including basic type variables, local variables, and object references (addresses) .

Run the local method (may not be java implementation, but c implementation method)

Program counter: When threads are switched, the execution position is recorded for re-execution later.

The relationship between the stack and the heap is that the contents of the stack are stacked, and the reference address of the stack is stacked.

Stack

A method in a class will have a stack frame in the stack. The stack frame contains the local variable table, operand stack, method exit, and dynamic link. The virtual machine releases space after the method is executed.

Local variable table: store variables

Operand stack: During calculation, it is pushed into the operand stack, and finally taken out from the top of the stack

Method exit: Specify the return address when the method ends.

Dynamic linking: part of the symbol reference is converted to direct reference during the class loading stage, and the other part is converted to direct reference during runtime. This part is called dynamic linking. (Static Analysis|Dynamic Linking)

 

Stack overflow: Method recursion can easily cause stack overflow. Because it is recursive, the method has not ended, so the variable is created all the time, and the stack space is full, which causes an overflow.

Stack overflow code:

public class Test {
	public void test(){
		String a;
		test();
	}
	public static void main(String[] args) {
		Test t  =new Test();
		t.test();
	}
}

 

heap

The heap stores objects and arrays, and all new ones are put in the heap.
The relationship between the stack and the heap is that the contents of the stack are stacked, and the reference address of the stack is stacked.
Heap exceeding the threshold is a common memory overflow OutOfMemoryError.
The heap is dynamically allocated memory, a discontinuous memory area, managed by the Java garbage collector.

public class Test {
	public static void main(String[] args) {
		List list = new ArrayList<>();
		while (true) {
			list.add(1);
		}
	}
}

The relationship between stack and heap: stack object content, stack object reference address. 

Garbage collection

Method of judging the death of an object

Methods of judging the death of an object: reference counting method and reachability analysis method.

The reference counting method is controlled by the counter value. When it is referenced, it will increase by 1, and the reference will be decremented by 1. Disadvantages: A refers to B, and B refers to A and cannot be recycled, which is a circular reference.

The reachability analysis method is to select a stable object as the GCROOT, and then find the reachable object, and reclaim it if it is unreachable. Disadvantages: generate memory fragmentation.

Garbage collection algorithm

Garbage collection algorithms include: reference counting method, mark-clear algorithm, copy algorithm, mark-compression (organization) algorithm, incremental algorithm.

 Reference counting method: When an object is referenced by others, its counter is incremented by 1, and the reference is decremented by 1, and the object's counter value is 0 and then recycled. Disadvantage: Circular references may not be recycled.

Mark removal algorithm: Find reachable objects according to the root node, and reclaim them if they are unreachable. Disadvantages: generate space debris.

Copy algorithm (used by the new-generation serial garbage collector): Two blocks of space per minute are copied to another area when reclaimed, and then this area is deleted.

Mark compression algorithm (used in the old age): It has made some optimizations on the basis of the mark-sweep algorithm. In a memory space, mark the reachable objects, compress them to one side of the memory, and then delete other objects so that no memory fragmentation occurs.

Garbage collector

Parallel Scavenge   replication algorithm, the important feature is: pay attention to the throughput of the system.

Parallel OLD    uses mark compression algorithm

CMS collector    mark-sweep algorithm The recovery pause time will be relatively small, but the throughput will be sacrificed accordingly. Suitable for B/S architecture

G1  Collector ( Garbage First)   G1 Collector is currently the latest garbage collector. Compared with CMS Collector, G1 Collector is based on the mark - compression algorithm , it will not generate memory fragmentation.

It divides the entire Java heap into multiple independent regions of equal size (Region). The region set is defined as the young generation and the old generation, but they are no longer a physical barrier.

 

jdk1.7 default garbage collector Parallel Scavenge (new generation) + Parallel Old (old generation)

jdk1.8 default garbage collector Parallel Scavenge (new generation) + Parallel Old (old generation)

jdk1.9 default garbage collector G1

Synchronized keywords

Synchronized principle

With javap disassembly, you can see the underlying JVM instructions. There are one monitorenter and two monitorexit instructions, which are lock and release locks. One moniterexit is normal, and another is abnormal.

There is also the process of lock upgrade.

Lock upgrade

The object can be roughly divided into three parts, namely the object header, instance variables and padding bytes.

The object header consists of MarkWord and Klass Point (type pointer). Klass Point is a pointer to the object's class metadata. Mark Word is used to store the runtime data of the object itself.

Instance variables store the attribute information of the object, including the attribute information of the parent class, aligned according to 4 bytes

Filling character, because the virtual machine requires that the object byte must be an integer multiple of 8 bytes, the filling character is used to make up this integer multiple

Deflection lock--"Lightweight lock--"Heavyweight lock

Specific: Not every time there is competition (single thread)-" Introduction of biased locks- there are multiple threads competing--" Introduction of lightweight locks- competing threads will spin and wait, if there are any Other more threads start to compete---" Introduction of heavyweight locks ---threads will block, but the CPU will no longer consume spin operations.

 

Bias lock

Before jdk1.6, Synchronized was still a heavyweight lock, and the performance was not very good. Hotspot found that there were not so many threads competing every time, so there was a biased lock.

The thread ID is placed in the mark word of the object header and the stack frame. When the same thread comes in again, it is found that it is the same ID, and it comes in directly.

If the same thread does not enter the synchronized block, it will check whether it is alive according to the content pointed to by Kclas.

    (1) If it dies, CAS will relock and update the new thread ID.

    (2) If it survives, it will go to the stack frame to see if it still needs to hold the lock object.

           (2.1) If you do not need to hold it anymore, revoke it and re-bias the new thread ID

             (2.2) If the lock still needs to be held, the thread is suspended, the biased lock is cancelled, and the lock is upgraded to a lightweight lock.

Biased lock can be cancelled by parameter configuration -XX:-UseBiasedLocking = false

Lightweight lock

If there are not many competing threads and the waiting time is not long, use a lightweight lock to wait for the lock to be released by spinning.

There are multiple lightweight locks:

   (1) In the case of threads, if the second thread comes in and finds that the object header of the lock object is already occupied, it will spin and wait. If the waiting time is long, it will be upgraded to a heavyweight lock.

    (2) The third thread comes in and finds that another thread is spinning and waiting, and it will also be upgraded to a heavyweight lock.

 

Note: The lock cannot be downgraded after it is upgraded!

Interview answer: Synchronized lock upgrade idea 1:

         1. This is an optimization after jdk1.6. The author of Hotspot found that not every time there are so many threads competing , it leads to the biased lock . The biased lock is the concept of an object header. There are markword and markword in the object header. kclass point , markword will store thread ID and other runtime information. When a thread comes in, cas updates the thread ID, but the lock will not be released, and the same thread can come in directly next time.
        2. If there are multiple threads competing, if cas fails at this time , it will first go to the object header to know if it is alive , and then go to the stack frame to verify whether it is viable . If it is still alive, Will be upgraded to a lightweight lock.

        3. Lightweight lock means that the thread will spin. If the number of spins increases, it will be upgraded to a heavyweight lock. Another is that if more threads come in and someone is spinning, they will also be upgraded to a heavyweight lock.

Comprehension aid:

Partial lock: You don't have to line up to go to the toilet, you are at home alone, you don't need to lock the door, and you come in directly every time. (Single thread)

Lightweight lock: A friend comes to the house, and a friend wants to go to the bathroom, just wait a while outside, and the door doesn’t need to be locked. (Small number of threads, less competition, short time, no blocking)

Heavyweight locks: A bunch of friends came to the house, all of them rushed to the toilet, so they locked the door. (A large number of threads compete and block)

 

 

Guess you like

Origin blog.csdn.net/x18094/article/details/114140817