The multi-threaded interview questions you may encounter are here (with answers)

The job search came to an end. During the period, I experienced many things and thought about many problems, and finally gained some heavy things-growth and some offers from Ali, Baidu, Jingdong (sp), Huawei and other factories. Fortunately, everything is back on track. Next, we have to summarize the experience so that it will not be in vain. Then some of the author’s written examination/interview experience and dry goods during this process will be published and shared with the public.
Multithreading—The multithreaded interview questions you may encounter are here (including answers)

**This article sorts out and summarizes some of the questions about concurrent programming that are often asked during the interview/written test, including basic knowledge points such as thread pools, concurrency control locks, concurrent containers, and queue synchronizers. **On the one hand It is convenient for oneself to review the past and learn the new. On the other hand, I also hope to provide a review reference for students who are looking for a job.

Interview questions (answers are for reference only)

How to stop a thread

  • Use volatile variables to terminate normal running threads + throw exception method/Return method
  • Use the interrupt method in combination with the interruptted/isinterrupted method to terminate the running thread + throw exception method/Return method
  • Use the interrupt method to terminate the thread that is blocking

What is a thread-safe class?

In the definition of thread safety, the core concept is correctness. When multiple threads access a class, no matter what scheduling method is used in the runtime environment or how these threads will execute alternately, and there is no need for any additional synchronization or coordination in the main calling code, this class can behave correctly Behavior, then this class is thread-safe.

Why are the thread communication methods wait(), notify() and notifyAll() defined in the Object class?

Object lock = new Object();
synchronized (lock) {
	lock.wait();
	...
}

The wait-notify mechanism is a communication mechanism between different threads on the premise of acquiring an object lock. In Java, any object can be used as a lock. Due to the arbitrary nature of the lock object, these communication methods need to be defined in the Object class.

Why wait(), notify() and notifyAll() must be called in a synchronized method or synchronized block?

The wait/notify mechanism relies on the Synchronized synchronization mechanism in Java, and its purpose is to ensure that the waiting thread can sense the modification of the shared variable made by the notification thread when it returns from Wait(). If it is not used within the scope of synchronization, java.lang.IllegalMonitorStateException will be thrown.

Three criteria for concurrency

  • Exceptions will not cause deadlock: When a thread is abnormal and has not been captured, the JVM will automatically release the lock occupied by the current thread, so it will not cause a deadlock due to the exception, and will release the CPU at the same time;
  • Objects are locked instead of references;
  • There must be notify if there is wait;

How to ensure thread safety?

  • By locking (Lock/Synchronized) to ensure synchronous mutual exclusive access to critical resources;
  • Use the volatile keyword, a lightweight synchronization mechanism, but does not guarantee atomicity;
  • Use immutable classes and thread-safe classes (atomic classes, concurrent containers, synchronous containers, etc.).

What is the role of the volatile keyword in Java

The special rules of volatile ensure that the new value can be immediately synchronized to the main memory and refreshed from the main memory immediately before each use, which guarantees the visibility of the memory, and in addition, prohibits instruction reordering. In addition, the synchronized keyword can also guarantee memory visibility.

Instruction reordering issues can cause thread safety issues in a concurrent environment. The volatile keyword avoids this problem by prohibiting instruction reordering. As for the Synchronized keyword, the program within its control range is exclusive during execution, and the instruction reordering problem will not have any effect on it, so in any case, it can guarantee the final correctness.

ThreadLocal and the memory leak caused by it

ThreadLocal is a thread binding mechanism in Java, which can provide a copy of the variable value for each thread that uses the variable, and each thread can change its own copy independently, without copying other threads There is a conflict.

Each thread has a member variable threadLocals of type ThreadLocal.ThreadLocalMap. This threadLocals stores all ThreadLocal variables and their corresponding values ​​related to the thread. That is to say, the ThreadLocal variable and its corresponding value are one of the Map. Entry, more bluntly, the Key of each Entry in threadLocals is the ThreadLocal variable itself, and Value is the value corresponding to the ThreadLocal variable.

What is a deadlock (Deadlock)? How to analyze and avoid deadlock?

Deadlock refers to a situation where more than two threads are blocked forever. This situation requires at least more than two threads and more than two resources.

To analyze the deadlock , we need to look at the thread dump of the Java application. We need to find out those threads whose status is BLOCKED and the resources they are waiting for. Each resource has a unique id , with this id we can find out which thread already has its object lock

What is the Java Timer class? How to create a task with a specific time interval?

Timer is a scheduler that can be used to schedule a task to be executed at a specific time in the future or periodically. TimerTask is an abstract class that implements the Runnable interface. We need to inherit this class to create our own timing tasks and use Timer to schedule its execution

What is a thread pool? How to create a Java thread pool?

A thread pool manages a group of worker threads, and it also includes a queue for placing tasks waiting to be executed. The thread pool can avoid the frequent creation and destruction of threads, reduce resource consumption, and improve the response speed of the system. java.util.concurrent.Executors provides several implementations of the java.util.concurrent.Executor interface for creating thread pools, which mainly involve four roles:

  • Thread pool: Executor
  • Worker thread: Worker thread, the run() method of Worker executes the run() method of Job
  • Task Job: Runable and Callable
  • Blocking queue: BlockingQueue

Lock optimization technology

The purpose of lock optimization technology is to share data more efficiently between threads, solve competition problems, and better improve program execution efficiency.

  • Spin lock (context switch is expensive): Mutual exclusion lock -> block -> release CPU, thread context switch cost more + shared variable lock time is shorter == Let the thread wait for a while through spinning, spin lock
  • Lock coarsening (a large lock is better than several small locks): Repeated and frequent locking/unlocking of the same object by a series of continuous operations will cause unnecessary performance loss. It is recommended to coarsen the lock
  • Generally speaking, the smaller the synchronization range, the better, so that other threads can get the lock as soon as possible, but there are still special cases.
  • Biased lock (there is a lock but there is no competition in the current situation): Eliminate data synchronization primitives in the absence of competition, and improve the performance of programs with synchronization but without competition.
  • Lock elimination (locks but no competition, redundant locks): JVM compilation optimization, eliminating locks without data competition

This is the end of this article. Friends who like it help me like and follow, thank you! !

Guess you like

Origin blog.csdn.net/doubututou/article/details/109120418