Concurrent programming (Java interview questions)

1. What is a process? What is a thread?

Process is the smallest unit of resource allocation, thread is the smallest unit of CPU scheduling, a process contains multiple threads

2, talk about the life cycle of the thread

Thread has five states: create, wait, run, block, end, there are three ways to create a thread, two have no return value, one has a return value, the first is to inherit the Thread class, and the second is to implement the Runnable interface, The third is created by Callable and Future (override the Call method of the Callable class, get the return value of Call through the get method), after the thread is created, the thread is put into a waiting state by calling the start method, when the thread is scheduled by the CPU Enter the running state. If the thread calls the sleep method or the wait method to enter the blocking state. Then use the interrupt method interrupt to throw an exception to wake up the sleeping thread, or notify and notifyAll to wake up the waiting thread and enter the object lock pool. There are three situations where the thread will end. The first is the end of the run method, the second is to call the stop method to force the end, and the third is to use the interrupt method interrupt to end the thread at a suitable place.

3. What are the five differences between wait () and sleep ()?

There are five differences: the first is that sleep will not give up cpu resources, wait will, the second is that sleep will not release the lock, wait will, the third is that sleep can be called at any location, the wait method can only be synchronized Called in a block or synchronous method, the fourth is to enter the wait state after wake-up from sleep, and to compete for locks in the object's lock pool after wake-up. The fifth difference is that the sleep method is a thread method, and wait is an Object method.

4. What is the difference between wait (), notify (), notifyAll ()?

thread to wait method releases the lock and let the CPU resources, notify wake random object lock a thread pool, notifyall wake up the object lock the pool
and some thread, the greater the probability of a higher priority thread scramble to lock ( setPriority () 1 has the lowest priority, 10 has the highest priority, the default value is 5
, thread.setPriority (1))

5. What is the role of Volatile?

Ensure visibility between threads, to prevent rearrangement instruction, each read modified variable when read directly from main memory (shared thread region), rather than
read from the working memory (thread private region, stack) of Fetch, so that the thread can ensure that the latest value is read every time. However, Volatile can only guarantee
visibility between threads, but not atomicity. If two threads copy variables into working memory at the same time and copy them to main memory after modification
, there will be a problem. Like just said, reading into the working memory is actually the working cache area that is copied. The working cache area is an abstract concept.
There is no division of this area in the jvm. The specific placement is determined by the virtual machine. As long as it conforms to the JMM specification.

6. Application scenarios of Volatile?

There is no need to guarantee thread safety. For example, the run method has a variable modified by Volatile as a switch. When the switch is false, it exits the loop.

7. What are the three differences between Volatile and Synchronized?

The first is that volatile is lightweight synchronization (not exclusive, atomicity is not guaranteed), synchronized is heavyweight synchronization (exclusive, CPU switching consumes resources) The second is the difference is that volatile does not guarantee atomicity, while synchronized guarantees atomicity To ensure visibility, the third is that volatile can only modify variables, synchronized can modify code blocks and methods

8. When will a deadlock occur? How to avoid deadlock?

There are four conditions for deadlock: mutual exclusion, non-preemption, request and hold, and loop wait. There are two ways to avoid deadlocks: the first is the order of locking must be consistent, and the second is to set a timeout for the lock.

9. How to set a timeout for the lock?

10. How to use code to realize producer and consumer problems?

Create a resource class, set the maximum number of resources to 10, the current number of resources is 0, there are remove and put methods in the class, remove method to determine whether the current number of resources is 0, call the wait method to wait for 0, Non-zero resource – finally use notify to wake up other threads (why not notifyall to wake up all? Because one wakes up is also random, all wake ups are also random contention for locks, of course, the smaller the number, the less resources are consumed), the put method is also In the same way, to determine whether the resource has reached the maximum value, wait if it reaches it, and resource ++ if not, and finally wake up other threads. The consumer and producer classes use a combination to call the remove and put methods of the resource class to create and start consumer producer threads, respectively

11. The realization principle of Synchronized?

Before jdk1.6, synchronized is a heavyweight, but after continuous optimization, it becomes very powerful after jdk1.6. The synchronized lock has four states: no lock, bias lock, lightweight lock, and heavyweight lock. As the competition state is gradually upgraded, it cannot be downgraded. When the lock is acquired for the first time, the lock information in the object header Mark word will be modified through CAS. The lock will be upgraded from CAS to a biased lock. Mark Word records the thread's Id. If Without competition from other threads, there is no need to lock and unlock through CAS, and the biased thread will always have the biased lock. When a thread wants to compete for a biased lock, lock cancellation will occur. If the thread holding the biased lock has exited the synchronized code block or is not active, then the thread holding the biased lock will be tentatively placed in a safe place and then released. Lock, and then wake up the thread holding the biased lock (interrupt?), The competing threads modify the biased thread Id in the Mark word through CAS to obtain the biased lock. If competition occurs and the thread holding the biased lock does not exit the synchronized code block, then the biased lock will be upgraded to a lightweight lock, and the JVM will open up a space for storing lock information in the stack of the biased thread, storing the copy of MarkWord in the object header MarkWord in the object header is replaced with a pointer to the lock information in the stack. When the lightweight lock is released
, MarkWord is replaced into the object head again, and then the thread that originally held the biased lock is awakened. The competing thread attempts to replace MarkWord with a pointer to the information in the stack. If the replacement succeeds, a lightweight lock is obtained. If the replacement fails, the spin fails, and the number of spins is upgraded to a heavyweight lock. The monitor heavyweight lock is based on the monitorenter and The monitorexit instruction is implemented, the monitorenter is inserted into the start position, and the monitorexit is inserted into the end position. The JVM needs to ensure that each monitorenter has a monitorexit associated with it, and each object has a monitor associated with it. When a monitor is held, The object will be locked. When the thread executes the monitorenter instruction, it attempts to acquire the ownership of the monitor corresponding to the object lock, that is, attempts to acquire the object lock.

12. What is the difference between this lock, object lock and class lock?

This lock locks the current instance, the object lock locks the specified object, the class lock locks the class object, Synchronized is the this lock when the ordinary method is modified, and User.class.wait () releases the lock, and the static method is decorated Is a class lock, you can specify the type of lock when decorating the code block, the essence is to use monitor

13. What are the common types of locks?

CAS lock: Three basic operands are used in the AS mechanism: memory address V, old expected value A, and new value B to be modified. When updating a variable, the value corresponding to the memory address V will be changed to B only when the expected value A of the variable and the actual value in the memory address V are the same. Spin lock: It is through CAS to continuously determine whether the lock condition is met. Optimistic locking: From the beginning, it is believed that the execution will be successful, and it is controlled by version number or timestamp. CAS is optimistic locking. Pessimistic locks: At the beginning, it was believed that it would not be executed successfully, and the contention for locks was first followed by the execution of business logic. Reentrant lock: After the outer layer acquires the lock, the inner layer does not need to acquire the lock again to avoid deadlock. ReentrantLock and synchronized are reentrant locks. Non-reentrant locks: After the outer layer acquires the lock, the inner layer must also reacquire the lock, which is prone to deadlock. Fair locks: Those who enter the object lock pool at different time periods acquire locks according to the rules of first-come-first-served locks. Unfair locks: Those who enter the object lock pool at different time periods acquire locks according to the rules of competing for locks.
Bias locks, lightweight locks, and heavyweight locks. Talk about the implementation principle of Synchronized. Segment lock: Talk about ConcrrountHashMap. Distributed locks: Redis, ZK, etc. Read-write lock: Don't allow other reads and writes when writing, and the service does not allow a reason when synchronizing with zk.

14. Talk about the three differences between ReetranLock and Synchronized?

ReentrantLock delegates all operations of the Lock interface to the Sync class. The Sync class inherits the AQS abstract class. Sync has two subclasses, one that supports fair locks and
one that supports unfair locks. Unfair lock is used by default. ReentrantLock.lock calls the NonFairSync.lock method (AQS only hands the
method of trying to acquire the lock to a subclass to implement lock unlock holdLock () to determine whether the lock is acquired). Generally, unlock () is written in the finally block to prevent deadlock

15. Four differences between ReetranLock and Synchronized?

The first difference: one is a class, one is a keyword, the second difference: one can determine whether the lock is acquired, one is not, the third difference: one is automatic transmission (specifying the start position and end position), one It is a manual block (decoration method and code block)
. The fourth difference: lock is an optimistic lock. Synchronized originally used a pessimistic lock. After jdk1.6, it becomes very powerful and can be upgraded.

16. The role of join ()

Blocking threads, generally used to ensure the execution order of threads

17. What is the difference between run () and start ()?

run () is just a simple method and does not create a thread, and the start method is to execute the run method after creating the thread

18. What is the difference between CycliBarriar and CountdownLatch?

The first difference is that the focus is different. CycliBarriar is generally used to block a group of threads until a certain state is executed. CountdownLatch is to let a thread wait for other threads
to complete the task before executing. The second difference is that CycliBarriar can be recycled CountdownLatch is one-time, will block the thread before 0

19. Common problems in multi-threaded environment?

Race condition: Simultaneously operate a non-thread-safe data, resulting in unexpected results
Deadlock: grab resources from each other
Livelock: let resources to each other, solve, first-come-first-served
hunger: insufficient resources

20. What is an atom?

For example, the AtomicInteger class can call methods to increment or decrement to ensure thread safety

21. What is a CAS lock?

CAS has 3 operands, memory value V, old expected value A, and new value B to be modified. If and only if the expected value A and the memory value V are the same, modify the memory value V to B, otherwise return V.
This is an optimistic locking of thinking, I believe it before it changes, no other threads to modify it; and Synchronized is a pessimistic lock, it thinks before it changes, a
there will be other threads to modify it, pessimistic locking low productivity.
There is a very obvious problem with CAS, namely the ABA problem;
if the variable V is A when it is first read, and it is checked that it is still A when preparing for assignment, it can indicate that its value has not been modified by other threads. ?
If it has been changed to B during this time, and then changed back to A, then the CAS operation will mis-task and it has never been modified. In response to this situation, the java concurrent package provides
a marked atomic application class AtomicStampedRefernce, which can ensure the correctness of CAS through the version of the variable value;

22. What are the common locks in the application layer?

synchronized锁、lock

23. Application scenarios of pessimistic locking?

When the amount of concurrency is high, optimistic locking is used if the response is fast, or it will succeed or fail quickly. If the retry cost is high, use pessimistic locking, which
can guarantee the success rate.
Pessimistic locking is suitable for reading less and writing more, optimistic locking is suitable for reading more and writing less

24. What happens to IO deadlock?

25. How to quickly determine whether it is an IO deadlock problem and not other problems?

26. Does CLH know? Virtual queue.

The virtual queue is not a real queue, but the pointer points to the next node, which looks like a queue

27. Why do double check locks need volatile?

28. Why can multi-threading improve efficiency?

29. If I open new threads indefinitely, will the efficiency of this program keep rising, or will it decline, or will it remain unchanged?

30. Synchronized is a single server to deal with concurrency issues, what about multiple servers?

31. Why wait (), notify (), notifyall () should be called in the synchronized code block

32. Optimization of synchronized by java virtual machine

Synchronized is a heavyweight lock before 1.6, and biased lock, lightweight lock, and adaptive spin lock were introduced after 1.6

33. How to share data between two threads

Create a global static variable
Pass reference by method

34. How to use wait correctly? if or while?

You should use while, otherwise wait for the first time, after waking up, go directly to the following process, you
need to judge whether the conditions are met before going down.

35. Why use multithreading? Multi-threaded application scenarios?

Multi-threading can improve CPU utilization. For example, when sending a text message during registration, you can send a
text message while processing business logic. There are also multiple file uploads and aop to write logs to es asynchronously.

36. How to detect deadlock?

jstack can indicate which place is deadlocked, jvm comes with tools

37. How to ensure that only one run () method is executed in multithreading? (*******)

38. What is a blocking queue? How to achieve?

Producer and consumer issues

39. What is ThreadLocal? What is the role? (*******)

40. The difference between synchronous and asynchronous

Synchronous: All operations are completed before they are returned to the user, for example: bank transfer
Asynchronous: No need to wait for all operations to be completed, then return the results to achieve partial refresh.

Published 51 original articles · Likes2 · Visits 1850

Guess you like

Origin blog.csdn.net/qq_42972645/article/details/105658158