“Crouching in a pit can enter a big factory” multi-threaded series – context, deadlock, high-frequency interview questions

Time:2021-11-25

Author: Hua Gie

WeChat official account: Java development zero to one

preface

In the last squatting series, we introduced the basic knowledge of multithreading. Is it different from your usual understanding.

80% of the basic interview questions of “squatting can enter a big factory” were wrong in the first question

Today, we will continue to explain the basic theoretical knowledge of multithreading. If you are a novice or don’t know much about multithreading, don’t think about going to the liver combat class. It’s useless. You can’t see the reason for any bug. Hua gie strongly recommends following this series (manual dog head protection).

Me: Yo hoo, why didn’t the dog leftover son cultivate at home today and accompany your girlfriend to write bugs in the company again

Gouyuzi: Hey, how can we not accompany our girlfriend? We are inseparable every day

Me:

Dog leftover son: while there is no one today, go and see you in the pit. I want to be honest with you.

text

Me: dog leftovers, please listen to the first question. What’s the difference between guard threads and user threads?

We should know that Java has two kinds of threads: daemon thread and user thread. The only difference between them is that when the virtual machine leaves, if all threads in the JVM are daemon threads, the JVM will exit automatically; However, if there is one or more non daemon threads, they will not exit.

Me: I asked you about notify yesterday. Do you know the difference between notify and notifyAll in Java? Or how do we choose which one to use?

I still remember yesterday. Your memory is OK. I forgot it.

That’s true,notifyIt is impossible to specify to wake up a specific thread (this is said on the Internet, I will follow, as to why I will tell you later), which may lead to the problem of signal loss. Only when a thread is waiting is its home, andnotifyAllIt will wake up all waiting threads and allow them to compete for locks. Although it is not efficient, it can ensure that at least one thread continues to execute. If you want to usenotify, you must ensure that the following two conditions are met.

  • A notification only needs to wake up a maximum of one thread.
  • All threads waiting to wake up have the same processing logic. Take chestnuts for example, you will understand that different threads created using runnable interface instances, or multiple instances of the same thread subclass new.

Me: don’t be complacent. These are appetizers. Let me ask you another question. Why can wait only be used in code blocks?

What? (heart beating)waitCan it only be used in code blocks? I don’t know. That’s… MaybewaitI’m a cleanliness freak. I like to be alone.

Me: you step on a horse

Oh… I remember. We can think the other way around. If wait is not required to be in the synchronization block, the following error may occur.

Let’s first look at the code of thread safe queue implemented by wait and notify:

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();
 
    //
    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }
 
    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}
  1. Consumer a calltake(), at this timebuffer.isEmpty()Is true;
  2. Consumer a enters while and callswait()Method, producer B calls a completegive()(i.e. buffer. Add (data) and notify ());
  3. Then consumer a calledwait(), but missed the call from producer Bnotify()
  4. If no other producer calls the give () method later, the online process of consumer a will wait all the time.

Me: I can’t help but praise you for this explanation. Do you know what a lock is in Java?

The concept of lock can also be seen by small partners after learning gie's volatile.

lockThis thing is very abstract. You can imagine it as a real lock. As for its anti-theft lock, gold lock or fingerprint lock, it doesn’t matter. Even if it is a straw rope, a bicycle or even a lump of that, it can be used as a lock.lockWhat is the external image is not important. What is important is the meaning it represents: whoever holds it has the right to independently access critical resources.

Me: do you know what thread deadlock is?

deadlockThat is, two or more threads are waiting for a resource to be released due to competing resources during execution. Therefore, the threads are blocked indefinitely, and the system is in a deadlock state.

As shown in the figure, thread a holds resource 2 and thread B holds resource 1. They both want to apply for each other’s resources at the same time, so the two threads will wait for each other and enter a deadlock state.

Me: do you know the four necessary conditions for deadlock?

What we don’t know, I’ll list it for you.

  1. mutual exclusion : threads (processes) are exclusive to the allocated resources, that is, only one process can occupy the resources at any time.
  2. Request and hold conditions: when a thread (process) is blocked due to a request for resources, it holds on to the obtained resources.
  3. Conditions of non deprivation: the resources obtained by a thread (process) cannot be forcibly deprived by other threads until they are used up. The resources are released only after they are used up.
  4. Cycle waiting condition: when a deadlock occurs, the waiting thread (process) must form a loop, which will cause permanent blockage.

Me: since you know the conditions for deadlock, you must know how to avoid it?

The so-called suit the remedy to the case, want toAvoid deadlock, you need any of the four necessary conditions of the destroyer.

  1. Destroy mutually exclusive conditions: this road is impassable, because we use locks to make them mutually exclusive.
  2. Destruction request and hold condition: apply for all resources at once.
  3. Destroy the conditions of non deprivation: the thread occupying resources can try to apply for other resources. If it fails to apply, it can actively release the resources it occupies.
  4. Break cycle waiting condition: resources are applied in a certain order. When resources are released, they are released in reverse order.

Me: this wave answered well. Did you prepare it secretly last night. Dog leftover son, please continue to listen to the questions. Do you know the context switching?

Please respect me. Please call me dog master later.

Speaking ofContext switching, then we need to know what it iscontext, franklycontextIt is the contents of CPU registers and program counters at a certain point in time.

expand: each thread has a program counter (record the next instruction to be executed), a set of registers (save the working variables of the current thread), and a stack (record the execution history, in which each frame saves a process that has been called but not returned).

register: register is the internal memory of the CPU, which is responsible for storing the tasks that have been, are being and will be executed. The number is small but the speed is fast. Corresponding to it is the relatively slow ram main memory outside the CPU.

Program counter: the program counter is a special register used to indicate the current execution position of the instruction sequence CPU. The stored content is the position of the instruction being executed or the position of the instruction to be executed next time.

Got a rough ideacontext, thatContext switchingThat’s simple. It means that after the current task is executed, the CPU time slice will save its state before switching to the next task, so that it can continue to execute when switching back to the task next time. The task is a context switch from saving to reloading.

If it is not very clear, it can be understood in the following three steps.

  1. Suspend a process and store the state (context) of the process in the CPU in memory;
  2. Retrieve the context of the next process in memory and reply the process in the register of the CPU;
  3. Jump to the position pointed by the program counter, that is, the position where the code executes when the process is interrupted, so as to recover the process.

Me: it’s so detailed. Suddenly it’s exciting. What problems will context switching bring?

After reading the above introduction, we should have a feeling that in the case of high concurrency, frequent context switching will lead to serial execution of the system and greatly reduce the running rate.

  • Direct consumption: CPU registers need to be saved and loaded, and the system scheduler code needs to be executed.
  • Indirect consumption: in order to speed up the execution speed, the CPU caches the commonly used data, but after the context is switched (that is, the CPU executes different codes of different threads), the originally cached content is largely useless, so the CPU will cache again, which also leads to the slow start-up speed after the thread is scheduled to run.

expand: in order to avoid the overhead caused by frequent context switching, the thread scheduler will set a minimum execution time for each scheduled thread, so as to reduce the number of context switching and improve performance. However, the disadvantage is obvious, that is, it will reduce the response speed.

Me: then tell me what volatile is?

No, no, I’m tired to death today. I need a rest. We’ll fight again tomorrow.

summary

Multithreading knowledge points are very large, involving many aspects, especially for small partners who have just come into contact with multithreadinglockcontextThis concept is very difficult to understand. If you want to really master it all, you need to delve into the knowledge involved in each problem, such asHow to implement producer consumer model with wait / notifyThread scheduling processHow java code is converted step by step and executed by CPUWhat’s more, what’s the principle of the above knowledge points,How does thread start and interrupt threadsWhat is the principle of communication between threads

These flowers giegiegie will gradually take you to master, and some big knowledge points will be taken out for a single explanation,I hope you will continue to pay attention, do not proofing during holidays, and continue to improve

Pay attention to prevent losing

The above is the whole content of this issue,If there are any mistakes, please leave a message for advice. Thank you very much。 I’m flower giegie. If you have any questions, please leave a message and discuss them at any time. I’ll see you next time.

The article is constantly updated. You can search it through wechatJava development zero to one“Read it for the first time, and continue to update Java interviews and various knowledge points in the future. Interested partners are welcome to pay attention, learn together, ha together.

It’s not easy to be original. How can you bear to whore for nothing,If you think this article is of some use to you, thank old fellow for this article.Click like, comment or forward, because this will be the driving force for me to output more high-quality articles. Thank you!

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]