Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

Time:2021-9-18

What is JUC

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

In Java, the thread part is a key point. The JUC mentioned in this article is also about threads. JUC is short for Java. Util. Concurrent toolkit. This is a toolkit for processing threads. JDK 1.5 began to appear.

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

Process and thread

process

Process is a running activity of a computer program on a data set. It is the basic unit for resource allocation and scheduling of the system and the basis of the structure of the operating system. In the contemporary computer architecture of thread oriented design, process is the container of thread. Program is the description of instructions, data and their organizational form, and process is the entity of program. It is a running activity of a program in a computer on a data set. It is the basic unit for resource allocation and scheduling of the system and the basis of the structure of the operating system. Program is the description of instructions, data and their organizational form, and process is the entity of program.

thread

Thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.

summary

Process: refers to an application running in the system; Once a program runs, it is a process; Process – the smallest unit of resource allocation.

Thread: the basic unit in which the system allocates processor time resources, or a unit execution flow executed independently within a process. Thread — the smallest unit of program execution.

For Java: thread, runnable, callable

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

Extension: can Java really start threads?

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
    //Calling the local method area calls the C + + method, so Java cannot start the thread
    private native void start0();

Concurrency and parallelism

The essence of concurrent programming: making full use of CPU resources

Concurrent

Concurrent (multithreaded operation of the same resource) CPU core simulates multiple threads, which is the world’s martial arts. Only fast can not be broken and can alternate quickly

parallel

Multiple people walk together, the CPU is multi-core, and multiple threads can be executed at the same time; Thread pool

summary

Concurrency: different code blocks are executed alternately

Parallelism: different code blocks are executed simultaneously

Thread state

public enum State {
//Rebirth
NEW,
//Run
RUNNABLE,
//Block
BLOCKED,
//Wait, wait, wait
WAITING,
//Timeout wait
TIMED_WAITING,
//Terminate
TERMINATED;
}

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

Wait / sleep difference

  • From different classes wait = > object sleep = > thread
  • About the release of the lock, wait will release the lock. Sleep sleeps. Sleep with the lock won’t release!
  • The scope of use is different. Wait must be in the synchronous code block, and sleep can be anywhere
  • Whether to catch exceptions wait does not need to catch exceptions sleep must catch exceptions

Three lock lock (key)

Traditional synchronized

package com.shu;

public class SaleTicketDemo01 {
    public static void main(String[] args) {
        //Concurrency: multiple threads operate on the same resource class and throw the resource class into the thread
        Ticket ticket = new Ticket();
        //@ functionalinterfacefunctional interface, JDK1.8 lambda expression (parameter) - > {code}
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 1; i < 40 ; i++) {
                ticket.sale();
            }
        },"C").start();
    }
}

//Resource class OOP
class Ticket {
    //Properties and methods
    private int number = 30;
    //How to sell tickets
//Synchronized essence: queue, lock
    public synchronized void sale(){
        if (number>0){
            System. Out. Println (thread. Currentthread(). Getname() + "sold the first" + (number -- + "ticket, remaining:" + number);
        }
    }
}

characteristic

  • Atomicity: atomicity means that one or more operations are either fully executed and the execution process will not be interrupted by any factor, or they will not be executed. Attention! During the interview, I often ask you to compare synchronized and volatile. The biggest difference between them is atomicity. Volatile does not have atomicity.
  • Visibility: visibility means that when multiple threads access a resource, the status and value information of the resource are visible to other threads.
  • Orderliness: the order of program execution is in accordance with the code.
  • Reentrant: Generally speaking, a thread can still repeatedly apply for a lock when it has a lock.

Synchronized underlying principle

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

  • Before understanding the lock implementation principle, first understand the object header and monitor of Java. In the JVM, objects exist in three parts: object header, instance data and filling them.
  • The instance data and its filling have nothing to do with synchronized. Let’s talk about it briefly here (I also learned it by reading in-depth understanding of Java virtual machine. Readers can read the relevant chapters of the book carefully). The instance data stores the attribute data information of the class, including the attribute information of the parent class. If it is the instance part of the array, it also includes the length of the array. This part of memory is aligned by 4 bytes; It is not necessary to fill it. Since the virtual machine requires that the starting address of the object must be an integer multiple of 8 bytes, the alignment filling is only to align the bytes.
  • The object header is the focus we need to pay attention to. It is the basis for synchronized lock implementation, because synchronized lock application, locking and release are related to the object header. The main structure of the object header is composed of mark word and class metadata address, whereMark WordThe hashcode, lock information, generation age or GC flag of the object are stored,Class Metadata AddressIs the class metadata that the type pointer points to the object, through which the JVM determines which class the object is an instance.
  • Locks are also divided into different states. Before JDK6, there were only two states: no lock and lock (heavyweight lock). After JDK6, synchronized was optimized and two new states were added. There are four states in total: no lock, bias lock, lightweight lock and heavyweight lock. Among them, no lock is one state. The lock type and status are recorded in the object header mark word. In the process of applying for lock and lock upgrade, the JVM needs to read the object’s mark word data.
  • Each lock corresponds to a monitor object. In the hotspot virtual machine, it is implemented by objectmonitor (c + +). Each object has a monitor associated with it. There are many ways to implement the relationship between the object and its monitor. For example, the monitor can be created and destroyed together with the object or automatically generated when the thread attempts to obtain the object lock. However, when a monitor is held by a thread, it is locked.
ObjectMonitor() {
   _header       = NULL;
   _ count        = 0;  // Lock counter
   _waiters      = 0,
   _recursions   = 0;
   _object       = NULL;
   _owner        = NULL;
   _ WaitSet      = NULL; // The thread in wait state will be added to_ WaitSet
   _WaitSetLock  = 0 ;
   _Responsible  = NULL ;
   _succ         = NULL ;
   _cxq          = NULL ;
   FreeNext      = NULL ;
   _ EntryList    = NULL ; // Threads in the state of waiting for lock block will be added to the list
   _SpinFreq     = 0 ;
   _SpinClock    = 0 ;
   OwnerIsThread = 0 ;
 }

Lock interface

Shock! Jingdong architects handwritten JUC technical notes, and everyone who read them said it was good!

package com.shu;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02{
    public static void main(String[] args) {
        //Concurrency: multiple threads operate on the same resource class and throw the resource class into the thread
        Ticket ticket = new Ticket();

        //@ functionalinterfacefunctional interface, JDK1.8 lambda expression (parameter) - > {code}
        new Thread(()->{for (int i = 1; i < 40 ; i++)
            ticket.sale();},"A").start();
        new Thread(()->{for (int i = 1; i < 40 ; i++)
            ticket.sale();},"B").start();
        new Thread(()->{for (int i = 1; i < 40 ; i++)
            ticket.sale();},"C").start();
    }
}

//Resource class OOP
class Ticket02{
    //Properties and methods
    private int number = 30;
    //Create lock
    Lock lock=new ReentrantLock();
    public  void sale(){
        //Lock
        lock.lock();
        try {
        if (number>0){
                System. Out. Println (thread. Currentthread(). Getname() + "sold the first" + (number -- + "ticket, remaining:" + number);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            //Unlock
            lock.unlock();
        }

    }
}

contrast

  • Synchronized built-in Java keyword, lock is a Java class
  • Synchronized cannot determine the status of obtaining the lock. Lock can determine whether the lock has been obtained
  • Synchronized will release the lock automatically. Lock must release the lock manually! If the lock is not released, it will deadlock
  • Synchronized thread 1 (lock acquisition, blocking), thread 2 (wait, silly, etc.); Lock lock doesn’t have to wait
  • Synchronized reentrant lock, non interruptible, unfair; Lock, reentrant lock, lock judgment, unfair (you can set it yourself)
  • Synchronized is suitable for locking a small number of code synchronization problems, and lock is suitable for locking a large number of synchronization codes!

last

Welcome to the official account: the bright future, the first line Java interview question summary, the knowledge point learning mind Guide + a 300 page PDF document’s Java core knowledge point summary! The contents of these materials are the knowledge points that the interviewer must ask during the interview. The chapter includes many knowledge points, including basic knowledge, Java collection, JVM, multithreading concurrency, spring principle, microservice, netty and RPC, Kafka, diary, design pattern, Java algorithm, database, zookeeper, distributed cache, data structure, etc.