The latest Java Concurrent Featured Interview Questions in 2020, which ones you still don’t know? (Including answer + mind map)

Java concurrent programming

 

1. Three elements of concurrent programming?

2. What are the ways to achieve visibility?

3. The value of multithreading?

4. What are the ways to create threads?

5. Comparison of the three ways of creating threads?

6. The state flow diagram of the thread

7. Java threads have five basic states

8. What is a thread pool? What are the ways to create it?

9. The creation of four thread pools:

10. What are the advantages of thread pools?

11. What are the commonly used concurrency tools?

12. The difference between CyclicBarrier and CountDownLatch

13. What is the role of synchronized?

14. The role of the volatile keyword

15. What is CAS

16. The CAS problem

17. What is Future?

18. What is AQS

19. AQS supports two synchronization methods:

20. What is ReadWriteLock

21. What is FutureTask

22, the difference between synchronized and ReentrantLock

23. What is optimistic lock and pessimistic lock

24. How does thread B know that thread A has modified the variable?

25, synchronized, volatile, CAS comparison

26. What is the difference between sleep method and wait method?

27. What is ThreadLocal? What is the use?

28. Why wait() method and notify()/notifyAll() method should be called in synchronized block

29. What are the methods for multi-thread synchronization?

30, thread scheduling strategy

31. What is the concurrency of ConcurrentHashMap

32. How to find which thread uses the longest CPU in the Linux environment

33. Java deadlock and how to avoid it?

34, the cause of deadlock

35. How to wake up a blocked thread

36. How does immutable objects help multithreading?

37. What is multi-threaded context switching

38. What happens if the thread pool queue is full when you submit a task

39. What is the thread scheduling algorithm used in Java

40. What is the thread scheduler (Thread Scheduler) and time slicing (TimeSlicing)?

41, what is spin

42. What is the Lock interface in the Java Concurrency API? What are its advantages over synchronization?

43. Thread safety of singleton mode

44. What is the role of Semaphore

45. What is the Executors class?

46. ​​Which thread is the thread class constructor and static block called?

47. Which is a better choice, synchronization method or synchronization block?

48. What exceptions can be caused by too many Java threads?

 

Concurrent programming knowledge points compiled a mind map

 

1. Three elements of concurrent programming?

(1) Atomicity

Atomicity refers to one or more operations, either all are executed and not interrupted by other operations during execution, or all are not executed.

(2) Visibility

Visibility means that when multiple threads manipulate a shared variable, after one thread modifies the variable, other threads can immediately see the result of the modification.

(3) Orderliness

Orderliness, that is, the order of execution of the program is executed in the order of the code.

 

2. What are the ways to achieve visibility?

Synchronized or Lock: Ensure that only one thread acquires the lock to execute code at the same time, and flushes the latest value to the main memory before the lock is released to achieve visibility.

3. The value of multithreading?

(1) Take advantage of multi-core CPU

Multi-threading can really give play to the advantages of multi-core CPUs, and achieve the purpose of making full use of the CPU, using multi-threading to accomplish several things at the same time without interfering with each other.

(2) Prevent blocking

From the perspective of program efficiency, a single-core CPU not only does not give play to the advantages of multi-threading, but it will switch the thread context due to multi-threading running on a single-core CPU, which reduces the overall efficiency of the program. But for single-core CPU, we still have to apply multi-threading, just to prevent blocking. Imagine that if a single-core CPU uses a single thread, then as long as the thread is blocked, for example, reading a certain data remotely, the peer has not returned and the timeout period is not set, then your entire program will be before the data is returned. Stopped running. Multithreading can prevent this problem. Multiple threads run at the same time, even if one thread's code execution is blocked for reading data, it will not affect the execution of other tasks.

(3) Easy to model

This is another advantage that is not so obvious. Suppose there is a big task A, single-threaded programming, then there are a lot of considerations, and it is troublesome to build the entire program model. But if you divide this big task A into several small tasks, task B, task C, and task D, build program models separately, and run these tasks separately through multi-threading, it is much simpler.

 

4. What are the ways to create threads?

(1) Inherit the Thread class to create a thread class

(2) Create thread class through Runnable interface

(3) Create thread through Callable and Future

(4) Created by thread pool

 

5. Comparison of the three ways of creating threads?

(1) Create multiple threads by implementing Runnable and Callable interfaces.

The advantages are:

The thread class only implements the Runnable interface or the Callable interface, and can also inherit from other classes. In this way, multiple threads can share the same target object, so it is very suitable for multiple same threads to process the same resource, so that CPU, code and data can be separated to form a clear model and better reflect The idea of ​​object-oriented.

The disadvantages are:

Programming is slightly more complicated. If you want to access the current thread, you must use the Thread.currentThread() method.

(2) Create multithreading by inheriting the Thread class

The advantages are:

It is easy to write. If you need to access the current thread, you don't need to use the Thread.currentThread() method. You can use this directly to get the current thread.

The disadvantages are:

The thread class has inherited the Thread class, so it can no longer inherit from other parent classes.

(3) The difference between Runnable and Callable

1. Callable specifies (override) method is call(), Runnable specifies (override) method is run().

2. Callable tasks can return values ​​after execution, while Runnable tasks cannot return values.

3. The Call method can throw exceptions, but the run method cannot.

4. Run the Callable task to get a Future object, which represents the result of asynchronous calculation. It provides a way to check whether the calculation is complete, wait for the completion of the calculation, and retrieve the result of the calculation. Through the Future object, you can understand the execution of the task, cancel the execution of the task, and get the execution result.

 

6. The state flow diagram of the thread

The life cycle of a thread and five basic states:

Selected Java Concurrency Interview Questions in 2019, which ones you still do not know  (Including answer and mind map)

 

7. Java threads have five basic states

(1) New state (New) : When the thread object pair is created, it enters the new state, such as: Thread t = new MyThread();

(2) Ready state (Runnable) : When the start() method (t.start();) of the thread object is called, the thread enters the ready state. The thread in the ready state only means that the thread is ready and waiting for the CPU to schedule execution at any time, not that the thread will execute immediately after executing t.start();

(3) Running state : When the CPU starts to schedule a thread in the ready state, then the thread can be actually executed, that is, it enters the running state. Note: The ready state is the only entry to the running state, that is, if a thread wants to enter the running state for execution, it must first be in the ready state;

(4) Blocked : For some reason, the thread in the running state temporarily gives up the right to use the CPU and stops execution. At this time, it enters the blocked state. Until it enters the ready state, it has a chance to be again by the CPU. Call to enter the running state.

According to the different causes of blocking, the blocking state can be divided into three types:

1) Waiting for blocking: the thread in the running state executes the wait() method to make the thread enter the waiting blocking state;

2) Synchronous blocking: the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads),

It will enter the synchronous blocking state;

3) Other blocking: The thread will enter the blocking state by calling sleep() or join() of the thread or issuing an I/O request. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread turns to the ready state again.

(5) Dead state (Dead) : The thread finishes its execution or exits the run() method due to an exception, and the thread ends its life cycle.

 

8. What is a thread pool? What are the ways to create it?

The thread pool is to create several threads in advance. If there are tasks to be processed, the threads in the thread pool will process the tasks. After processing, the threads will not be destroyed, but will wait for the next task. Since the creation and destruction of threads consume system resources, you can consider using thread pools to improve system performance when you want to create and destroy threads frequently.

Java provides an implementation of the java.util.concurrent.Executor interface for creating thread pools.

 

9. The creation of four thread pools:

(1) newCachedThreadPool creates a cacheable thread pool

(2) newFixedThreadPool creates a fixed-length thread pool, which can control the maximum concurrent number of threads.

(3) newScheduledThreadPool creates a fixed-length thread pool to support timing and periodic task execution.

(4) newSingleThreadExecutor creates a single-threaded thread pool, which will only use a single worker thread to perform tasks.

 

10. What are the advantages of thread pools?

(1) Reuse existing threads to reduce the overhead of object creation and destruction.

(2) It can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, and avoid excessive resource competition and blockage.

(3) Provide functions such as timing execution, regular execution, single thread, and concurrent number control.

 

11. What are the commonly used concurrency tools?

(1)CountDownLatch

(2)CyclicBarrier

(3)Semaphore

(4)Exchanger

 

12. The difference between CyclicBarrier and CountDownLatch

(1) CountDownLatch simply means that a thread waits until the other threads it is waiting for have completed execution and call the countDown() method to notify the current thread before it can continue execution.

(2) cyclicBarrier is that all threads wait until all threads are ready to enter the await() method, all threads start executing at the same time!

(3) The counter of CountDownLatch can only be used once. The counter of CyclicBarrier can be reset using the reset() method. Therefore, CyclicBarrier can handle more complex business scenarios. For example, if an error occurs in the calculation, the counter can be reset and the threads can be executed again.

(4) CyclicBarrier also provides other useful methods, such as getNumberWaiting method to get the number of threads blocked by CyclicBarrier. The isBroken method is used to know whether the blocked thread is interrupted. Return true if interrupted, otherwise return false.

 

13. What is the role of synchronized?

In Java, the synchronized keyword is used to control thread synchronization, that is, in a multithreaded environment, to control the synchronized code segment from being executed by multiple threads at the same time. synchronized can be added to a piece of code or method.

 

14. The role of the volatile keyword

For visibility, Java provides the volatile keyword to ensure visibility. When a shared variable is modified by volatile, it will ensure that the modified value will be updated to main memory immediately. When other threads need to read it, it will go to the memory to read the new value. From a practical point of view, an important role of volatile is to combine with CAS to ensure atomicity. For details, please refer to the classes under the java.util.concurrent.atomic package, such as AtomicInteger.

 

15. What is CAS

CAS is the abbreviation of compare and swap, which is what we call compare exchange.

cas is a lock-based operation, and it is an optimistic lock. Locks in java are divided into optimistic locks and pessimistic locks. Pessimistic lock is to lock the resource, and the next thread can only access it after a thread that previously acquired the lock releases the lock. Optimistic locking adopts a broad attitude, processing resources in some way without locking, for example, by adding version to the record to obtain data, the performance is greatly improved compared with pessimistic locking.

CAS operation consists of three operands-memory location (V), expected original value (A) and new value (B). If the value in the memory address is the same as the value of A, then the value in the memory is updated to B. CAS obtains data through an infinite loop. If in the first round of the loop, the value in the address obtained by the thread a is modified by the thread b, then the thread a needs to spin, and it may not have a chance to execute until the next loop.

Most of the classes under the java.util.concurrent.atomic package are implemented using CAS operations (AtomicInteger, AtomicBoolean, AtomicLong).

 

16. The CAS problem

(1) CAS can easily cause ABA problems

A thread a changes the value to b, and then changes it to a. At this time, CAS thinks that there is no change, but it has changed. The solution to this problem can be identified by the version number, and version is incremented by 1 for each operation. . In java5, AtomicStampedReference has been provided to solve the problem.

(2) The atomicity of the code block cannot be guaranteed

The CAS mechanism guarantees the atomic operation of a variable, but cannot guarantee the atomicity of the entire code block. For example, if you need to ensure that 3 variables are updated atomically together, you have to use synchronized.

(3) CAS causes an increase in CPU utilization

As mentioned before, CAS is a cyclic judgment process. If the thread has not obtained the status, the CPU resources will always be occupied.

 

17. What is Future?

In concurrent programming, we often use the non-blocking model. In the previous three implementations of multithreading, whether it is inheriting the thread class or implementing the runnable interface, there is no guarantee that the previous execution results will be obtained. By implementing the Callback interface and using Future, you can receive multi-threaded execution results.

Future represents the result of an asynchronous task that may not be completed. For this result, a Callback can be added to perform the corresponding operation after the task execution succeeds or fails.

18. What is AQS

AQS is the abbreviation of AbustactQueuedSynchronizer. It is a Java-improved low-level synchronization tool class. It uses an int type variable to represent the synchronization state and provides a series of CAS operations to manage the synchronization state.

AQS is a framework for building locks and synchronizers. AQS can be used to easily and efficiently construct a large number of synchronizers for a wide range of applications, such as ReentrantLock, Semaphore, and others such as ReentrantReadWriteLock, SynchronousQueue, FutureTask, etc. It is based on AQS.

 

19. AQS supports two synchronization methods:

(1) Exclusive type

(2) Shared

This makes it easy for users to implement different types of synchronization components, such as exclusive types such as ReentrantLock, shared types such as Semaphore, CountDownLatch, and combined types such as ReentrantReadWriteLock. In short, AQS provides the bottom support for use, how to assemble and realize, users can play freely.

 

 

20. What is ReadWriteLock

First of all, make it clear, it's not that ReentrantLock is bad, but ReentrantLock has some limitations. If you use ReentrantLock, it may be to prevent data inconsistency caused by thread A writing data and thread B reading data, but in this way, if thread C is reading data and thread D is also reading data, reading data will not change the data, so there is no need Locking, but still locking, reducing the performance of the program. Because of this, the ReadWriteLock was born. ReadWriteLock is a read-write lock interface, and ReentrantReadWriteLock is a specific implementation of the ReadWriteLock interface, which realizes the separation of read and write. The read lock is shared, and the write lock is exclusive. There is no mutual exclusion between read and write. Write and read, and write and write are mutually exclusive, which improves the performance of reading and writing.

 

21. What is FutureTask

This is actually mentioned before, FutureTask represents an asynchronous operation task. A specific implementation class of Callable can be passed into FutureTask, which can wait to obtain the result of the asynchronous operation task, determine whether it has been completed, and cancel the task. Of course, because FutureTask is also an implementation class of Runnable interface, FutureTask can also be placed in the thread pool.

 

22, the difference between synchronized and ReentrantLock

Synchronized is the same keyword as if, else, for, while, and ReentrantLock is a class, which is the essential difference between the two. Since ReentrantLock is a class, it provides more and more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. ReentrantLock's scalability than synchronized is reflected in several points:

(1) ReentrantLock can set the waiting time for acquiring the lock, so as to avoid deadlock

(2) ReentrantLock can obtain various lock information

(3) ReentrantLock can flexibly implement multiple notifications

In addition, the lock mechanism of the two is actually different. The bottom layer of ReentrantLock calls the Unsafe park method to lock, and the synchronized operation should be the mark word in the object header. I am not sure about this.

 

23. What is optimistic lock and pessimistic lock

(1) Optimistic lock: Just like its name, it is optimistic about the thread safety issues caused by concurrent operations. Optimistic lock believes that competition does not always occur, so it does not need to hold the lock. It will compare-replace the two This action is used as an atomic operation to try to modify the variables in the memory. If it fails, it means that there is a conflict, and there should be corresponding retry logic.

(2) Pessimistic lock: still like its name, it is pessimistic about thread safety issues caused by concurrent operations. Pessimistic lock believes that competition will always occur, so every time a resource is operated, it will hold an exclusive The lock is just like synchronized, no matter if it is three or seven twenty-one, you can operate the resource directly when you lock it.

 

24. How does thread B know that thread A has modified the variable?

(1) volatile modified variable

(2) Synchronized modification method of modifying variables

(3)wait/notify

(4) while polling

 

25, synchronized, volatile, CAS comparison

(1) Synchronized is a pessimistic lock, which is preemptive and will cause other threads to block.

(2) Volatile provides visibility of multi-threaded shared variables and prohibits instruction reordering optimization.

(3) CAS is an optimistic lock based on conflict detection (non-blocking)

 

26. What is the difference between sleep method and wait method?

This question is often asked. Both the sleep method and the wait method can be used to give up the CPU for a certain amount of time. The difference is that if the thread holds the monitor of an object, the sleep method will not give up the monitor of this object, and the wait method will give up this. Object monitor

 

27. What is ThreadLocal? What is the use?

ThreadLocal is a local thread copy variable tool class. It is mainly used to map the private thread and the copy object stored by the thread, and the variables between the threads do not interfere with each other. In high concurrency scenarios, stateless calls can be realized, especially suitable for variable values ​​that are dependent on each thread. Scenario for completing the operation. Simply put, ThreadLocal is a way of changing space for time. In each Thread, a ThreadLocal.ThreadLocalMap implemented by the open address method is maintained. Data is isolated and data is not shared. Naturally, there is no thread safety problem.

 

28. Why wait() method and notify()/notifyAll() method should be called in synchronized block

This is mandatory by the JDK. Both the wait() method and the notify()/notifyAll() method must acquire the object lock before calling

 

29. What are the methods for multi-thread synchronization?

Synchronized keyword, Lock implementation, distributed lock, etc.

 

30, thread scheduling strategy

The thread scheduler selects the thread with the highest priority to run, but it will terminate the thread if the following conditions occur:

(1) The yield method is called in the thread body to give up the right to occupy the cpu

(2) The sleep method is called in the thread body to make the thread sleep

(3) Thread is blocked due to IO operation

(4) Another higher priority thread appears

(5) In a system that supports time slices, the thread’s time slice runs out

31. What is the concurrency of ConcurrentHashMap

The concurrency of ConcurrentHashMap is the size of the segment. The default is 16, which means that up to 16 threads can operate ConcurrentHashMap at the same time. This is also the biggest advantage of ConcurrentHashMap over Hashtable. In any case, Hashtable can have two threads to obtain Hashtable at the same time. Data?

 

32. How to find which thread uses the longest CPU in the Linux environment

(1) Get the pid, jps or ps -ef | grep java of the project

(2) top -H -p pid, the order cannot be changed

 

33. Java deadlock and how to avoid it?

A deadlock in Java is a programming situation in which two or more threads are permanently blocked. A Java deadlock situation occurs with at least two threads and two or more resources.

The root cause of the deadlock in Java is: a cross closed loop application occurred when applying for a lock.

 

34, the cause of deadlock

(1) Multiple threads involve multiple locks, and these locks are crossed, so it may lead to a closed loop of lock dependence.

For example: A thread applies for lock B when it has acquired lock A and has not released it. At this time, another thread has acquired lock B, and must acquire lock A before releasing lock B. Therefore, the closed loop occurs and it falls into a deadlock loop. .

(2) The default lock request operation is blocking.

Therefore, in order to avoid deadlock, it is necessary to carefully examine all methods in the classes of these objects when there are multiple object locks crossing, whether there is the possibility of loops that cause lock dependence. In short, try to avoid calling delay methods and synchronization methods of other objects in a synchronized method.

 

35. How to wake up a blocked thread

If the thread is blocked by calling wait(), sleep() or join(), you can interrupt the thread and wake it up by throwing InterruptedException; if the thread encounters IO blocking, nothing can be done, because IO is the operating system Realized, there is no way for Java code to directly touch the operating system.

 

36. How does immutable objects help multithreading?

There is a problem mentioned earlier. Immutable objects ensure the memory visibility of the object. The reading of immutable objects does not require additional synchronization means, which improves the efficiency of code execution.

 

37. What is multi-threaded context switching

Multi-threaded context switching refers to the process in which CPU control is switched from an already running thread to another thread that is ready and waiting to obtain CPU execution rights.

 

38. What happens if the thread pool queue is full when you submit a task

Distinguish here:

(1) If you are using an unbounded queue LinkedBlockingQueue, that is, an unbounded queue, it does not matter, continue to add tasks to the blocking queue to wait for execution, because LinkedBlockingQueue can be regarded as an infinite queue, which can store tasks infinitely

(2) If you are using a bounded queue such as ArrayBlockingQueue, the task will first be added to the ArrayBlockingQueue. When the ArrayBlockingQueue is full, the number of threads will be increased according to the value of maximumPoolSize. If the number of threads is increased, the number of threads still cannot be processed, and the ArrayBlockingQueue continues to be full, then It will use the rejected policy RejectedExecutionHandler to process the full tasks, the default is AbortPolicy

 

39. What is the thread scheduling algorithm used in Java

Preemptive. After a thread runs out of CPU, the operating system will calculate a total priority based on thread priority, thread starvation and other data and allocate the next time slice to a thread for execution.

 

 

40. What is the thread scheduler (Thread Scheduler) and time slicing (TimeSlicing)?

The thread scheduler is an operating system service that is responsible for allocating CPU time for threads in the Runnable state. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Time slicing refers to the process of allocating available CPU time to available Runnable threads. Allocating CPU time can be based on thread priority or thread waiting time. Thread scheduling is not controlled by the Java virtual machine, so it is a better choice to control it by the application (that is, don't let your program depend on thread priority).

 

41, what is spin

Many codes in synchronized are just simple codes, and the execution time is very fast. At this time, waiting threads are locked may be a not worthwhile operation, because thread blocking involves switching between user mode and kernel mode. Since the code in synchronized executes very fast, let the thread waiting for the lock not be blocked, but do a busy loop on the boundary of synchronized, which is spin. If you do multiple busy cycles and find that the lock has not been obtained, block again. This may be a better strategy.

 

42. What is the Lock interface in the Java Concurrency API? What are its advantages over synchronization?

The Lock interface provides more scalable lock operations than synchronization methods and synchronization blocks. They allow more flexible structures, can have completely different properties, and can support multiple related types of conditional objects.

Its advantages are:

(1) Can make the lock more fair

(2) The thread can respond to interrupts while waiting for the lock

(3) You can let the thread try to acquire the lock, and return immediately or wait for a period of time when the lock cannot be acquired

(4) Locks can be acquired and released in different ranges and in different orders

 

43. Thread safety of singleton mode

The old-fashioned question, the first thing to say is that the thread safety of the singleton mode means that an instance of a certain class will only be created once in a multithreaded environment. There are many ways to write singleton mode, let me summarize:

(1) The writing of the hungry Chinese singleton pattern: thread safety

(2) The writing method of the lazy singleton pattern: non-thread safe

(3) The writing of the double check lock singleton mode: thread safety

 

44. What is the role of Semaphore

Semaphore is a semaphore, its function is to limit the number of concurrent code blocks. Semaphore has a constructor that can pass in an int type integer n, which means that a certain piece of code can only be accessed by n threads at most. If it exceeds n, please wait until a certain thread finishes executing this code block, and the next thread Re-enter. It can be seen that if the int type integer n=1 passed in the Semaphore constructor, it is equivalent to becoming a synchronized.

 

45. What is the Executors class?

Executors provides some tool methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory and Callable classes. Executors can be used to easily create thread pools

 

46. ​​Which thread is the thread class constructor and static block called?

This is a very tricky and cunning question. Remember: the construction method and static block of the thread class are called by the thread where the thread class is new, and the code in the run method is called by the thread itself.

If the above statement confuses you, let me give you an example. Assuming that Thread1 is new in Thread2 and Thread2 is new in main function, then:

(1) The construction method and static block of Thread2 are called by the main thread, and the run() method of Thread2 is called by Thread2 itself

(2) The construction method and static block of Thread1 are called by Thread2, and the run() method of Thread1 is called by Thread1 itself

 

47. Which is a better choice, synchronization method or synchronization block?

Synchronous block, which means that the code outside the synchronous block is executed asynchronously, which improves the efficiency of the code more than the entire method of synchronization. Please know a principle: the smaller the scope of synchronization, the better.

 

48. What exceptions can be caused by too many Java threads?

(1) The life cycle overhead of threads is very high

(2) Consume too much CPU resources

If the number of runnable threads is more than the number of available processors, then some threads will be idle. A large number of idle threads will occupy a lot of memory, putting pressure on the garbage collector, and a large number of threads will also produce other performance overhead when competing for CPU resources.

(3) Reduce stability

JVM has a limit on the number of threads that can be created. This limit value will vary with different platforms, and is subject to multiple factors, including JVM startup parameters, the size of the request stack in the Thread constructor, and the underlying operation System restrictions on threads, etc. If these restrictions are broken, an OutOfMemoryError may be thrown.


In response to the knowledge points asked in the above interview, I have summarized most of the interview questions and answers involved in the Internet company Java programmer interview. Documents and architecture materials are shared with everyone, hoping to help you review before the interview And finding a good job also saves everyone's time to search for information on the Internet to learn

The following is a three-month time-consuming process to sort out nearly a thousand Java interview questions for multiple companies in 2020 and more than 400 pages of pdf documents, covering: Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, Spring Boot, Spring Cloud, RabbitMQ, Kafka, Linux and other technology stacks

 

Friends who want to get this complete pdf: After you like it, you can private message [interview document] (be sure to pay attention to me, otherwise there is no way to reply to stranger private messages)

 

 

 

Guess you like

Origin blog.csdn.net/bjmsb/article/details/108733025