Sort lock-related knowledge points in the concurrent package

Source: Internet
Author: User

I have read several multi-threaded things before. Today I have reviewed it, read the fourth lock of Java concurrent programming, and review the flow of thread status, as shown below:

Lock-related entry points: Lock and condition.

Lock is an interface that provides abstract methods such as lock and unlock;

The concurrent package provides many lock implementations of different policies, which are used to make the process of obtaining and using exclusive resources more efficient than the traditional synchronized synchronization block.

The traditional synchronized mechanism is that when a thread obtains the built-in monitor lock of an object, other threads can only be at the entrance of the synchronization block.StampIn the blocked status.

If the waiting time is short, it is not a problem. However, if there are many waiting threads in the queue and the waiting time is expected to be long, other threads are idling, because the threads in the blocked State do not release the system resources occupied, asynchronous notification mechanisms can be used to break these threads, that is, switching to the waiting state and waiting for the arrival of the activation signal, and releasing the occupied resources.

The lock () method in the concurrent package is implemented through locksupport. Park (), even if the thread is changed to the waiting state. Reference thread status flow chart

Further, there may be many scenarios that require long waiting for the same lock. For example, a conveyor belt between the producer and the consumer is a dedicated resource, and the same write lock is obtained every time Q is written. However, there are two situations (or status/condition) that can lead to long waits: one is that Q is full and cannot join the queue (the producer should be waiting ), the other is that Q is empty and cannot leave the team. (The consumer should wait ).

Condition provides the preceding long wait scenariosScoreThe capabilities of the scheduling thread provide the wait (await) and activation (signal) functions (similar to the wait and Y in the traditional synchronized mechanism, note 1 ).

Threads of different roles can be scheduled according to different conditions.

So far, the structure of multiple conditions derived from one lock is described clearly. (For condition translation, note 2)

Several abstract locks:

Readwritelock: When a thread applies for a read lock, as long as the write lock is not held by other threads, it will immediately have a read lock. When a thread applies for a write lock, other threads cannot hold the read lock or write lock; otherwise, they will wait. The write lock is an exclusive lock, and the read lock can be held by multiple threads at the same time.

Reentrantlock: in the case of recursion, some locks need to be repeatedly acquired by a thread to form a "reentrant lock ".

Reentrantreadwritelock: provides both of the preceding features.

Several lock-related scenarios:

In actual programming, for some common scenarios, direct lock-oriented programming is still too arrogant, so the following tools are born to provide intuitive support for various scenarios.

  • Semaphore: provides a limited number of resources for multi-threaded competition. It also provides different competitive strategies (fair/unfair), similar to scenarios where parking spaces are tight.
  • Mutex (mutex): When the semaphore is 1, it is similar to a scenario where there is only one restroom.
  • Latch (literal: locking, bolt): Wait until n target threads trigger an event (countdownlatch:
    Synchronization aid that allows one or more threads to wait until a set of operations being stored med in other threads completes .) for countdownlatch, the action corresponding to the trigger event is to subtract 1 from the counter, that is, countdownlatch. countdown (); note that it cannot be reset, so it is one-time. Similar to the finishing line of A-meter sprint, wait until all the players hit the line and then execute the awards ceremony.
  • Barrier (literal: Barrier and barrier): blocks the first arriving thread on several slices to wait until all target threads arrive, so that all threads can continue to execute concurrently from the same aspect
    : A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.) Note that it can be reset, so each section can reuse the same javasicbarrier. This post mentions that javasicbarrier can easily help implement complicated parallel computing scenarios such as mapreduce. It is really a sentence, but is there any image examples in real life? I thought about Normandy login. Assume that the German army has n lines of defense in Normandy. To defeat each line of defense, different numbers of Allied soldiers are required to log in and assemble and initiate a charge. At that time, the Allied forces had obtained absolute control of the sea road, soldiers are continuously sent ashore and sacrificed in the battle. In the above example, every Allied soldier is a thread, and the line of defense is barrier. Each line of defense is broken when a specified number of living threads arrive at the assembly, and then contract to form the next line of defense, it is equivalent to the threshold value of Reset barrier failure.
Note 1: What is the difference between wait and await? This article describes the role of traditional wait. This article attempts to describe the differences between the two. Essentially, the thread releases the lock and enters the wait state. There are two main differences. First, compared with synchronized, lock can derive multiple conditions to trigger await, which is more intuitive in semantics. Second, after the traditional wait is called, either a thread is randomly activated through notify, either use policyall to activate all threads to allow them to compete for locks, while await supports richer lock competition strategies, such as fair (queuing in await order) and unfair ones. Note 2: In most articles Translate condition into "condition", Feel stiff. Condition also has a situation, status, state (a state of being), such as race condition,
Wiki translation is a "competitive condition". I think it should be translated into a "Competitive State" (intended to emphasize the harm caused by the multi-thread competition ); it can be interpreted as "race hazards" (so there will be a Race Hazard alias) or "concurrent security problems ". In section 1st of the English wiki, the competition status is harmless (non-critical ). After reading a lot of explanations about race condition, most of them talk about variable value instability due to unknown read/write execution sequence in concurrency, that is, the 1st point sequencing problems mentioned in this article (I think of the happens-before law in the corrected jmm, all about sequence). However, a rare article mentions the 2nd point of race condition, locking problems. (I vaguely remember reading an article by Lao Zhao, about live lock caused by poor tail recursion, which belongs to the category of race condition .) ======================================== Recently summarized the transaction isolation level of the database, the transaction has four acid dimensions, and the isolation level is the same. It is suggested that the readwritelock implementation should belong to the read
Committed (shared read lock + exclusive write lock ). Of course, it depends on how to use it. If the shared read lock is released until the transaction ends, instead of releasing the read lock immediately after the transaction reads the resource, it can also be considered as Repeatable read. For details, refer to 5.1.2.1. Isolation levels.

In addition, we noticed that Doug Lea's earlier concurrent package implementation, readwritelock has multiple implementations, mainly providing different strategies for the read/write lock competition, which are excerpted from this:

Although the basic read-write locking operations are straightforward, many decisions must be made, which may affect the effect of read-write locking in a given application. Examples of these policies include:

    • When the writer releases the write lock, both Reader and writer are in the waiting state. At this time, determine whether to grant read lock or write lock. Writer is generally preferred because the expected write time is shorter and less frequent. Reader priority is not very common, because if the reader is as frequent and persistent as expected, it will lead to a long latency for write operations. Fairness or order-based implementation are also possible.
    • When the reader is active and the writer is waiting, determine whether to grant read lock to the reader with the read lock request. Reader first delays writer indefinitely, while writer first reduces possible concurrency.
    • Are you sure you want to re-enter the lock: Can you use a thread with a write lock to re-obtain it? Can I get read lock while keeping write lock? Can I re-enter the write lock itself?
    • Can I downgrade the write lock to read lock when other writer interference is not allowed? Can I upgrade read lock to write lock over other waiting reader or writer?

All of these situations should be taken into account when evaluating whether a given implementation is suitable for your application.

Most of the Internet is read-write-less, so the current default implementation is adopted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.