Java Multi-threaded concurrency series lock deep Understanding

Source: Internet
Author: User
Tags finally block


In a previous blog post: Java Multi-threading, concurrency Series (synchronized) synchronization and locking mechanism。 This paper introduces the synchronized and simple locking mechanism in Java, introduces the polling lock and timing lock in the lock module, and briefly reviews

    • Poll Lock: Use Trylock to get two locks, and if not, then rewind and try again.

    • Timing Lock: When the lock is requested, you can set a time-out period, and if the lock is not obtained after this time, it will not continue to jam but give up the task.

The fairness of the lock

In a fair lock, the thread acquires the lock in the order in which they make the request.

It seems to forget that there is also an interruptible lock and selectable granularity lock

Interruptible Lock

Just as a timed lock acquisition operation can use an exclusive lock in a time-limited operation, an interruptible lock-fetching operation can also use a lock in an operation that can be canceled. The Lockinterruptibly method can maintain a response to interrupts while acquiring a lock, and because it is contained in lock, there is no need to create other types of non-interruptible blocking mechanisms.

The standard structure of an interruptible lock acquisition operation is slightly more complicated than a normal lock acquisition operation, since it requires two try blocks (the standard try-finally-lock mode can be used if interruptedexception is thrown in an interruptible lock-fetch operation).

Lockinterruptibly is used in the following program to implement Sendonshareline in the program to invoke him in a task that can be canceled.

 Public  BooleanSendonsharedline (String message)throwsinterruptedexception{lock.lockinterruptibly ();Try{returnCancellablesendonsharedline (message); }finally{Lock.unlock (); }    }Private BooleanCancellablesendonsharedline (String message)throwsInterruptedexception{...}

Performance considerations (built-in lock and display lock)

In JDK1.5, synchronized is inefficient in performance. Because this is a heavyweight operation, the biggest impact on performance is the implementation of blocking, and the operations of the suspend and resume threads need to be completed in the kernel state, which brings a lot of pressure to the concurrency of the system. In contrast, using the lock object provided by Java provides a higher performance. Brian Goetz a set of throughput comparisons between the two locks in JDK1.5, single-core processors, and dual Xeon processors, and found that the synchronized throughput dropped very seriously in a multi-threaded environment, And the reentranklock can be basically maintained at the same stable level. But it's better to say that synchronized has a lot of room for optimization than reetrantlock performance. So to the JDK1.6, has changed, to synchronize added a lot of optimization measures, there is adaptive spin, lock elimination, lock coarsening, lightweight lock, biased lock and so on. resulting in synchronize performance on JDK1.6 is no worse than lock. Officials have also said they are more supportive of synchronize, and that there is room for optimization in future releases, so it is recommended that the synchronized be used in order to synchronize synchronized in the event that demand is fulfilled.

The performance comparison is as follows: Figure from Java concurrent Programming combat


The fairness of the lock consideration

Two fairness choices are available in the Reentrantlock constructor: creating an unfair lock or a fair lock.

Fair lock.

The threads will acquire the lock in the order in which they made the request, and the newly issued request thread will be placed in the wait queue.

Non-fair lock

Allow queue jumping on the basis of fair lock, when a thread acquires a lock, if the state of the lock becomes available while the request is made, the thread skips all waiting threads in the queue and acquires the lock.

We don't want all the locks to be fair. Although fairness is a good behavior, it is not always good for the efficiency of the system. Look at an example like this

Wait for the queue to rival1-2-3-4At the end of the queue there are four waiting threads, threads0Just executing the end, at which point a thread5Come on, according to the method of fair locking, then5Will enter the waiting queue1-2-3-4-5, and then remove the thread from the opponent1, but if, using an unfair approach, the thread5At the same time, the thread5Executes directly, skips the wait queue, then reduces the suspended thread5and Recovery threads1Overhead, throughput gains

In a highly competitive environment, the performance of an unfair lock is higher than the performance of a fair lock because there is a serious delay between recovering a suspended thread and actually starting execution of the thread.

The performance of the two locks, such as the figure from Java concurrent Programming combat


Choose between synchronized and Reentrantlock

It is known from the above that Reentrantlock has the same semantics as the built-in lock in addition to the lock and memory, and it also provides some other functions, including timed lock waits, interruptible lock waits, fairness, and the ability to unlock non-block structures, which reentrantlock appear to outperform the built-in locks. However, built-in locks still have a big advantage in some situations

    • Built-in locks are familiar to many developers and are compact and concise, and in many existing programs, if the two mechanisms are mixed, they are not only confusing, but also prone to errors
    • The risk of reentrantlock is higher than the synchronization mechanism, and if you forget to call unlock in the finally block, the code surface can run, but it has actually buried a time bomb and is likely to risk other code.

When to use Reentrantlock: Consider using Reentrantlock only if the built-in lock does not meet the requirements, including: Timed, polled, and interruptible lock acquisition, fair queue, and non-block structure lock

Java Multi-threaded concurrency series lock deep Understanding

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.