The opening is introduced

Hello everyone, the public account [Java Geek Mind] will soon sort out some Java high frequency interview questions to share with partners, also hope to see partners in the job search process can be enough! This chapter mainly aims at Java some multithreaded high frequency interview questions to share.

Notice: the public account [Java geek thinking] is sending book welfare activities, pay attention to the public account and participate in welfare activities! Only those who participate in this activity can participate in the big benefit at the end of the year. Don’t miss it

Q1:

What is the CAS algorithm?

**CAS (compare and swap) **

Java uses the CAS instruction of the CPU and JNI to perform the non-blocking algorithm on Java to implement atomic operations (essentially spin operations, repeated until success). Other atomic operations are performed using similar properties.

CAS has three key operational values: memory value V, expected value A, and value B to be modified.

The content of the memory value V is changed to B if and only if the expected value A is the same as the memory value V, otherwise nothing is done.

The disadvantages of CAS are also obvious:

In high concurrency situations, if many threads repeatedly try to update a variable, but do not update it successfully, they keep looping (spin), this can put a lot of stress on the CPU.

The CAS mechanism guarantees atomicity only for a variable, not for an entire code block. For example, the synchronized keyword must be used to ensure that all three variables are updated atomically.

For example, thread A takes A glass of water and puts it on the table, but it is called away by something else, and releases the lock. Thread B passes by, sees the water on the table, takes A half drink, and then fills up another glass and puts it on the table. It’s still A glass of water, but it’s no longer the same glass of water, and thread A is finished, turns around and sees the same glass of water on the table, but doesn’t know that the water has been replaced. This is a typical ABA problem, and there are many similar scenarios. This situation has a significant impact on the results of operations in scenarios that depend on process values. This is the biggest problem with CAS.

  • Excessive CPU overhead

  • Atomicity of code blocks cannot be guaranteed

  • ABA problem

Q2:

What is AQS?

AQS (AbstractQueuedSynchronizer)

AQS is a synchronization framework provided under the JDK for implementing BLOCKING locks and associated synchronizers based on FIFO wait queues. This abstract class is designed to be the base class for synchronizers that use atomic int values to represent state.

If you have seen similar CountDownLatch class source code implementation, will find its internal have a Sync inherited AbstractQueuedSynchronizer inner class. CountDownLatch is a synchronizer implemented based on the AQS framework. There are several similar synchronizers available under JUC (Semaphore, for example).

The core idea of AQS is to modify the current lock state based on volatile variables such as volatile int state and atomic operations performed by the Unsafe tool. The synchronizer internally relies on a FIFO bidirectional queue to complete the queuing of resource acquisition threads.

Data structures in AQS – nodes and synchronization queues

The node is added to the synchronization queue

Change of first node

Q3:

What is the use of the volatile keyword?

Java provides the volatile keyword to ensure visibility. When a shared variable is volatile, it guarantees that the value is immediately updated to main memory, and that it will read the new value when another thread needs to read it. The main principle is the use of memory instructions.

  • LoadLoad reordering: a processor performs an L1 read and then an L2 read; But the other processor sees first L2 then L1;

  • StoreStore reordering: a processor performs a W1 write operation and then a W2 write operation. But the other processor sees first W2 and then W1;

  • LoadStore reordering: a processor performs a L1 read followed by a W2 write; But the other processor sees first W2 and then L1;

  • StoreLoad reordering: a processor performs a W1 write operation followed by an L2 read operation; But the other processor sees L2 first and then W1.

Q4:

Describe how atomicity, visibility, and order are guaranteed by the volatile keyword.

A Release barrier precedes volatile writes, and then a Store barrier follows to ensure that volatile writes do not reorder any reads or writes prior to Release. The Store barrier ensures that, once volatile writes are complete, Flush processor cache is executed immediately.

A Load barrier precedes volatile reads. This ensures that any read of a volatile variable that has been modified by another processor must be loaded from the other processor’s cache (or main memory) into its own local cache to ensure that the read is up-to-date. After that, a Acquire barrier is added, and any read and write operations that follow volatile reads are reordered with volatile reads.

Contrast this with volatile read-write memory barriers, which have a similar meaning.

Acquire block is LoadLoad block + LoadStore block;

The Release barrier is essentially the StoreLoad barrier plus StoreStore barrier.

Q5:

Describe briefly the principle of the synchronized keyword.

Synchronized is a way of implementing mutually exclusive synchronization implemented by the JVM. If you look at the compiled bytecodes of blocks modified with the synchronized keyword, you will find: Monitorenter and Monitorexit bytecode instructions are generated by the compiler before and after compilation of a synchronized block.

When the virtual machine executes the Monitorenter instruction, it first tries to acquire the lock on an object. If the object is not locked or the current thread already owns the lock, it increments the lock counter by 1.

When monitorexit is executed, the counter -1 is locked; When the counter is 0, the lock is released. If the object acquisition fails, the current thread blocks and waits until the lock is released by another thread.

Q6:

What’s the difference between CountDownLatch and CyclicBarrier?

  • CountDownLatch’s counter can only be used once. CyclicBarrierd counters can be reset using the reset() method. So CyclicBarrier can handle more complex business scenarios. For example, if a calculation error occurs, the counter can be reset and the threads can recalculate.

  • CyclicBarrier also provides other useful methods, such as the getNumberWaiting() method to get the number of threads blocked by a CyclicBarrier. The isBroken() method can be used to know if a blocking thread has been interrupted.

  • CountDownLatch blocks the main thread, CyclicBarrier does not block the main thread, only child threads.

  • The CountDownLatch relies on an external force (a counter, a starting gun) to control the thread, while a CyclicBarrier is the equivalent of controlling the thread itself. Here’s an example:

    • CountDownLatch: Have A room full of stones, there are 7 lock door, then the team consisted of seven people to enter the room A, and seven other people were holding the key of team B, then the group A first 7 individuals must wait for group B sent seven keys, then put out seven locks were opened, the group A seven talented person able to enter the room to get the gems.

    • CyclicBarrier: There is a room full of gems, there are also 7 locks on the door, and then 7 people have to go to another room and complete a task for each of the 7 people to get a lock, after completing the task, the 7 people can open the 7 locks, enter the room to get the gems.

Tomorrow, will introduce some in-depth knowledge of multithreading, long press the TWO-DIMENSIONAL code to follow me ~

I wish you all can get the desired offer!

Focus, don’t get lost

If you think the article is good, please pay attention to it, like it, and save it. Your support is the motivation for my creation. Thank you all.

If there is a problem with the article, please don’t be stingy, welcome to point out the message, I will check and modify in time.

If you want to know more about me, you can search “Java Geek thinking” on wechat to follow me. Every 8:00 on time push technical articles, so that your way to work is not lonely, and there are monthly book activities, to help you improve hard power!