How does a Reentrant Lock actually differ from Synchronized?

The basic principle of the lock is to achieve a goal: let all the lines can see a certain mark. Synchronized implements this goal by setting markers in the object’s head, and is a JVM native method of locking, Reentrant Lock and all of its implementation classes based on the Lock interface are implemented by using a Volitile modifier of int type, And guarantee that each line can have the visibility and original modification of the INT, its quality is based on the so-called AQS frame frame.

What is AQS frame frame

The AQS (Abstract Queued Synchronizer class) is a frame for constructing locks and synchronizers, Reentrant Lock, Read Write Lock, Semaphore, CountDownLatch, Even early Future tasks are constructed based on AQS.

  • Internally, AQS defines a volatile int state variable to indicate synchronization status: When using lock method, if state= 0, it indicates that no other line has shared resource lock, it can obtain the lock and set state= 1. If state= 1, it indicates that the shared variable is being used before the line, and other lines must be added to the same step queue to wait.

  • AQS completes the queuing work of line-process lock acquisition through a double-step linked list constructed by the inner class of Node. When the line-process lock acquisition fails, It was added to the end of the line.

  • The Node class is a wrapper for a line that wants to query the same code, including the line itself and its state called wait Status (there are five different values, the classification table indicates whether the line is blocked, Each Node Node is connected to its preV Node and next Node, and the next Node is quickly called after the lock is released. Is a FIFO process.

  • The Node class has two constants, SHARED and EXCLUSIVE, which represent the SHARED and EXCLUSIVE modes of the table. The shared mode is a lock that allows simultaneous operation of several lines (the signal quantity Semaphore is implemented based on the shared mode of AQS), In the single-occupancy mode, only one line can operate on the shared resource at the same time segment, and more redundant lines need to queue up (e.g., Reentran Lock).

  • AQS constructs the inner Condition Object class. When Condition calls wait(), the line will be added to the waiting queue. When Condition calls signal(), lines will race from wait-waiting queue to same-step queue.

  • AQS and Condition each maintain different columns, and when Lock and Condition are used, it is actually the phase shift of the two columns.

Compare Synchronized and Reentrant locks as thoroughly as you can

Reentrant Lock is an implementation of Lock, which is a mutually exclusive synchronized Lock.

In terms of power, Reentrant Lock is more precise than Synchronized

(because Synchronized can be used as a general object), or even as a higher power than Synchronized, as in:

  • Waiting to be broken: when the line with a lock does not release the lock for a long time, the line in waiting can be selected to release the line, and the step block with unusual length is very useful for processing.

  • Try to get the lock with time lapse: get the lock within the specified time range, if there is still no time to get the lock, return.

  • Can be used to determine whether there is a line waiting for the lock.

  • Different from Synchronized, when the line path to the lock is broken, it can be loud enough to be broken, and the abnormal will be thrown out, and the lock will be released at the same time.

  • The lock can be realized.

From the Angle of lock release, Synchronized is realized on the JVM layer, but can be controlled by some monitoring tools to control Synchronized lock, The JVM automatically releases the lock when the code execution is abnormal. “Of”, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “,”

In terms of Angle of sexual performance, Synchronized has lower performance than Reentrant Lock in early stage, and has a large difference in sexual performance compared to Reentrant Lock in many scenes. In Java 6, however, Synchronized performs better than Reetrant Lock when the competition is not intense. Synchronized performance drops several times in high contention situations, but maintains a constant state of Reetrant Lock performance.

How is Reentrant Lock Reentrant?

Reentrant Lock internally defines Sync (Sync implements both AQS and AOS, which provides a mutual exclusion holding formula), In fact, it is the time of locking. Through CAS algorithm, the line path object is placed in a two-way linked list. Each time the lock is acquired, See if the ID of the line before maintenance is the same as the ID of the line before maintenance, and then you can re-enter it.

In addition to Reetrant Lock, which other JUC tools have you touched and developed?

Concurrent delivery (JUC) is commonly referred to as java.util.concurrent and its sub-packages, which contain all kinds of Java base tools and classes. The main package contains several aspects:

  • It provides Count Down Latch, Cyclic Barrier, Semaphore, etc., which is higher than Synchronized and can be implemented with more abundant and multi-line operation in the same step.

  • Concurrent Hash Map, Concunrrent Skip List Map with sequence, Or through the class like quick photo machine to make real line security dynamic state number group Copy On Write Array List, etc., all kinds of line security capacity.

  • · Providing Array Blocking Queue, Synchorous Queue, Priority Blocking Queue, etc., all of which were issued and implemented.

  • A large Executor box can be used to create a variety of different types of routing pools, and to adjust the flow of tasks.

Talk about Read Write Lock and Stamped Lock.

Although Reentrant Lock and Synchronized are simple and practical, there is a certain limitation on the behavior of the line, whether it does not occupy, or whether it only occupies. In the real world, there are times when you don’t need a lot of competing write operations. Instead, Java provides read-write locking for the granularity of step optimization and write operations.

Read – write locking is based on the principle that multiple read operations do not need to exclude each other. If the write lock is held by a certain line, the read lock will not be acquired. This ensures that no disputed data will be read if the other party is to be operated.

Read Write Lock represents a pair of locks. The underlying structure is a data structure based on read-write Lock implementation. When the number of data is large and the number of reads is high and the number of writes is low, Can be better than pure same-step convex:

Read and write lock looks like a fine particle than Synchronized, but in real life should be used, its appearance is not as good as people would like, the main is also because of the larger than the opening pin.

As a result, the JDK later included Stamped Lock, which also supported improved read modes along with Stamped read-write locks. Optimal reading is based on a false assumption. In most cases, the reading operation does not contradict the writing operation. The logic of the reading operation first tries to modify it and then verifies whether it enters the writing mode by using the validate method. If there is no entry, to avoid the opening of the pin; If entered, try to obtain read lock.

How do I make Java routines work the same way? Which pedometer have you solved? Please separate them from each other.

The synchronization in JUC has three main members: Count Down Latch, Cyclic Barrier, and Semaphore, through which work between many lines can be realized. Count Down Latch to allow one or more lines to wait until some operation is completed. Look at a few scenes:

  • In running competitions, judges should wait until all runners (” other courses “) have reached the end point (the target) before they can count the ranks and award prizes.

  • Modeling and development, I need to initiate 100 lines to visit a site at the same time, I want them to be simultaneous, not one by one.

    “Count Down Latch” refers to the number of the Latch. “Count Down” is used by the waitlist to “Count Down” the counter. The waitlist waits with “await” the Latch. A simple example:

Cyclic barriers are called Cyclic barriers, which actually allow a set of lines to wait until a state is completed, and when all waiting lines are released, Cyclic barriers can be reused. The Cyclic Barrier’s canonical field is used to wait and bind.

The main method of the Cyclic Barrier is await(), and each time await() is invoked, the count decreases by one and blocks the current line. When the count decreases to 0, the stopper is released and all the stopper lines on the Cyclic Barrier begin to move.

After that, if we call await() again, the count will change to n-1 again and a new round will start again, which is Cyclic meaning. Cyclic Barrier. Await () carries a loopback value to indicate the first line to reach the Barrier as the preceding line.

To give an example:

Semaphore, the Java version of the signal quantity implementation, is used to control the number of simultaneous access lines, to limit the purpose of universal resource access, The idea is to acquire a license through acquire(), wait if it doesn’t have one, and release() release a license.

If the value of Semaphore is initially set to 1, then a line can enter the mutually exclusive state through acquire, which is inherently similar to the mutual exclusion. However, this distinction is not always obvious. For example, the mutual exclusion lock has a possessor, and for Semaphore, there is similarity, But it does not exist in the holder of true and true meaning, except in our development and packaging.

Cyclic barriers and Count Down latches look very similar.

There is a definite similarity between them, and the main difference lies in:

  • The Count Down Latch cannot be repositioned, so there is no way to reuse it, and the Cyclic Barrier has no such restriction, so it can be reused.

  • The base operation of the Latch is grouped to Count Down/ await, and the line stopper of the await waits until the Count Down is sufficient. It doesn’t matter if you’re counting Down in one thread or multiple threads, just count Down enough times. The basic operations of the Cyclic Barrier are marshalled as await, and only when all the partners invoke await will they continue the task and automatically reposition the line.

  • The purpose of the Latch is to make one Latch wait until N other latches have reached a specific Latch. Public Cyclic Barrier(int parties, Runnable Barrier Action); The same results can be achieved by doing things in the new path. The purpose of Cyclic Barrier is to make N lines wait for each other until all of them reach a certain state. The N latches are then followed by successive latches (similar effects can also be achieved through Count Down latches).