Java Concurrency 2

Source: Internet
Author: User
Tags cas finally block


The new lock mechanism introduced in Java 5 is an explicit mutex in--java.util.concurrent.locks: The Lock interface, which provides a wider range of locking operations than synchronized. The lock interface has 3 classes that implement it: Reentrantlock, Reetrantreadwritelock.readlock, and Reetrantreadwritelock.writelock, which are re-entry locks, read locks, and write locks. Lock must be explicitly created, locked, and disposed in order to be able to use more features, which are typically instantiated with Reentrantlock. In order to ensure that the lock will eventually be released (possibly with an exception), place the mutex inside the try statement block and release the lock in the finally statement block, especially if there is a return statement, the return statement must be placed in a try sentence to ensure that unlock () does not occur prematurely To expose the data to a second task. Thus, the general form of lock locking and release locks is as follows:

Lock lock = new Reentrantlock ();//default use of an unfair lock, if you want to use a fair lock, you need to pass in the parameter true

........

Lock.lock ();

try {

Update the state of an object

Catch exceptions, revert to the original immutable constraint if necessary

If there is a return statement, put it here.

finally {

Lock.unlock (); The lock must be released in the finally block

     Lock lock = new Reentrantlock ();//The default is to use an unfair lock, if you want to use a fair lock, you need to pass in the parameter True     .... Lock.lock ();     try {          //update the state of the object         //catch exception, revert to the original invariant constraint        if necessary//if there is a return statement, put it here    } finally {            lock.unlock ();        The lock must be released in the Finally Block    }


Reetranklockcomparison with synchronized
Performance Comparison

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.


below is an analysis of the following two kinds of locking mechanism of the underlying implementation strategy.

The main problem of mutex synchronization is the performance problem caused by thread blocking and wake-up, so this synchronization is called blocking synchronization, which is a pessimistic concurrency policy, that is, the thread obtains an exclusive lock. An exclusive lock means that other threads can only rely on blocking to wait for the thread to release the lock. When the CPU conversion thread is blocked, it causes the thread context switch, and when there are many threads competing for the lock, the CPU's frequent context switches are inefficient. This concurrency strategy is used by synchronized.

With the development of the instruction set, we have another option: optimistic concurrency based on conflict detection, popularly speaking is advanced operation, if no other thread contention shared data, then the operation succeeds, if the shared data is contention, there is a conflict, Then other compensation measures (the most common compensation measure is to constantly regain, until the trial succeeds), many implementations of this optimistic concurrency policy do not need to suspend the thread, so this synchronization is called non-blocking synchronization. This concurrency strategy is used by Reetrantlock.

In an optimistic concurrency strategy, the two steps, which require operation and conflict detection, are atomic and are guaranteed by hardware directives, which use CAS operations (Compare and Swaps). After JDK1.5, the Java program can use CAS operations. We can further study the source code of Reentrantlock, we will find that one of the more important way to obtain a lock is compareandsetstate, which is actually called the CPU to provide special instructions. Modern CPUs provide instructions to automatically update shared data and detect interference from other threads, and Compareandset () replaces the lock with these. This algorithm, called a non-blocking algorithm, means that failure or suspension of one thread should not affect the failure or suspension of other threads.

Java 5 introduces special atomic variables such as injected Automicinteger, Automiclong, automicreference, etc., which provide such things as compareandset (), Methods such as Incrementandset () and getandincrement () use CAS operations. Therefore, they are all atomic methods that are guaranteed by hardware instructions.


Use comparisonThe basic syntax, reentrantlock and synchronized very similar, they all have the same thread re-entrant features, but the code is a little different, a display of the API level of the mutex (lock), A mutex that behaves as a native syntactic level (synchronized). Reentrantlock relative to synchronized, there are some more advanced features, mainly the following three items:

1, waiting to be interrupted: when the thread holding the lock does not release the lock for a long time, the waiting thread can choose to discard the wait and instead handle the other things, which is helpful for processing the synchronization blocks that are very time-executed. While waiting for the mutex generated by the synchronized, it will always block, can not be interrupted.

2, can achieve a fair lock: When multiple threads are waiting for the same lock, they must be queued in the order in which they are requested, while non-fair locks do not guarantee this, and any thread that waits for a lock has a chance to acquire a lock when the lock is released. Synchronized locks are not fair when locked, Reentrantlock is also an unfair lock by default, but you can require a fair lock by constructing method Reentrantlock (ture).

3. Locks can bind multiple conditions: The Reentrantlock object can bind multiple condition objects at the same time (name: condition variable or conditional queue), and in synchronized, The Wait () and notify () or Notifyall () methods of the lock object can implement an implied condition, but if you want to associate with more than one condition, you have to add a lock extra, and Reentrantlock does not need to do this. You only need to call the Newcondition () method multiple times. And we can also bind the condition object to determine which threads are being notified by the current thread (that is, other threads that are bound to the condition object).

the book "Java Concurrency Programming Practice" gives the best time to use Reentrantlock:

When you need the following advanced features, you should use: A timed, polled, and interruptible Lock acquisition operation, a fair queue, or a lock that is not a block structure. Otherwise, please use synchronized.

Source: < java concurrency programming 20: Concurrency new features-lock lock and condition variables (with code)-Orchid Pavilion Storm column-Blog channel-csdn.net>  

From for notes (Wiz)

Java Concurrency 2

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.