Java concurrency (basic knowledge)-display lock and synchronization tool class

Source: Internet
Author: User

Java concurrency (basic knowledge)-display lock and synchronization tool class
The show Lock interface is a newly added interface in Java 5.0, which is defined as follows: public interface Lock {void lock (); void lockInterruptibly () throws InterruptedException; boolean tryLock (); boolean tryLock (long time, TimeUnit unit) throws InterruptedException; void unlock (); Condition newCondition ();} unlike the built-in locking mechanism, lock provides an unconditional, round-robin, timed, and disruptive Lock acquisition operation. All locking and unlocking methods are displayed. ReentrantLock implements the Lock interface. Compared with the built-in Lock, ReentrantLock has the following advantages: it can interrupt the Lock acquisition operation and set the timeout time when obtaining the Lock. The following code provides the standard usage of the Lock interface: Lock lock = new ReentrantLock ();... lock. lock (); try {...} finally {lock. unlock (); 1.1. The round-robin locks and timed locks can be acquired by the tryLock method. Compared with the unconditional lock acquisition method, it has a complete error response mechanism. The tryLock method is described as follows: boolean tryLock (): This lock is obtained only when the lock is idle. If the lock is available, the lock is obtained and the return value is true immediately. If the lock is unavailable, this method immediately returns false. Boolean tryLock (long time, TimeUnit unit) throws InterruptedException: gets the lock if the lock is idle within the specified wait time and the current thread is not interrupted. If the lock is available, this method returns true immediately. If the lock is unavailable, the current thread will be disabled for Thread Scheduling purposes, and the thread will remain in sleep state until one of the following three conditions occurs: the lock is obtained by the current thread; or another thread interrupts the current thread and supports the interruption of lock acquisition; or if the lock is obtained after the specified wait time is exceeded, the return value is true. If the current thread has already set the thread interruption status when it enters this method, or is interrupted when it gets the lock and supports the interruption of the lock, InterruptedException will be thrown, it also clears the interrupted status of the current thread. If the specified wait time is exceeded, the return value is false. If time is less than or equal to 0, this method will not wait. In built-in locks, deadlock is a serious problem. The only way to recover a program is to restart the program, the only way to prevent deadlocks is to avoid inconsistent lock sequence when constructing a program. The timed and round-robin locks provide another option: Use tryLock () first () try to get all the locks. If you cannot get all the required locks, release the obtained locks and try again to get all the locks. The following example demonstrates how to use tryLock to avoid deadlocks: use tryLock to obtain two locks. If they cannot be obtained at the same time, roll back and try again. Public boolean transferMoney (Account fromAcct, Account toAcct, DollarAmount amount, long timeout, TimeUnit unit) throws limit, InterruptedException {long fixedDelay = 1; long randMod = 2; long stopTime = System. nanoTime () + unit. toNanos (timeout); while (true) {if (fromAcct. lock. tryLock () {try {if (toAcct. lock. tryLock () {try {if (fromAcct. getBalance (). compareTo (amount) <0) throw new InsufficientFundsException (); else {fromAcct. debit (amount); toAcct. credit (amount); return true ;}} finally {toAcct. lock. unlock () ;}} finally {fromAcct. lock. unlock () ;}} if (System. nanoTime () <stopTime) return false; NANOSECONDS. sleep (fixedDelay + rnd. nextLong () % randMod) ;}1.2. The lockInterruptibly method can maintain the response to the interruption while obtaining the lock. The method is described as follows: void lockInterruptibly () throws Interrup TedException: if the current thread is not interrupted, the lock is obtained. If the lock is available, the lock is obtained and immediately returned. If the lock is unavailable, the current thread is disabled for the purpose of Thread Scheduling and remains in sleep state until one of the following two conditions occurs: the lock is obtained by the current thread; or another thread interrupts the current thread and supports the interruption of lock acquisition. If the current thread has already set the thread interruption status when it enters this method, or is interrupted when it gets the lock and supports the interruption of the lock, InterruptedException will be thrown, and clear the interrupted status of the current thread. 1.3 In addition to the Lock interface, the read-write Lock Java 5 also adds the ReadWriteLock interface, that is, the read-write Lock. The interface is defined as follows: public interface ReadWriteLock {Lock readLock (); lock writeLock ();} The read/write Lock allows concurrent execution by multiple read threads, but does not allow concurrent execution by the write and read threads, or concurrent execution by the write and write threads. The following example uses ReentrantReadWriteLock to wrap the Map so that it can be securely shared among multiple threads: public class ReadWriteMap <K, V> {private final Map <K, v> map; private final ReadWriteLock lock = new ReentrantReadWriteLock (); private final Lock r = lock. readLock (); private final Lock w = lock. writeLock (); public ReadWriteMap (Map <K, V> map) {this. map = map;} public V put (K key, V value) {w. lock (); try {return map. put (key, value);} fina Lly {w. unlock () ;}} public V remove (Object key) {w. lock (); try {return map. remove (key);} finally {w. unlock () ;}} public void putAll (Map <? Extends K ,? Extends V> m) {w. lock (); try {map. putAll (m);} finally {w. unlock () ;}} public void clear () {w. lock (); try {map. clear ();} finally {w. unlock () ;}} public V get (Object key) {r. lock (); try {return map. get (key) ;}finally {r. unlock () ;}} public int size () {r. lock (); try {return map. size ();} finally {r. unlock () ;}} public boolean isEmpty () {r. lock (); try {return map. isEmpty ();} fina Lly {r. unlock () ;}} public boolean containsKey (Object key) {r. lock (); try {return map. containsKey (key);} finally {r. unlock () ;}} public boolean containsValue (Object value) {r. lock (); try {return map. containsValue (value);} finally {r. unlock () ;}} synchronization tool Class 2.1, locking is a synchronization auxiliary class, before completing a group of operations being executed in other threads, it allows one or more threads to wait. Initialize CountDownLatch with the given count. Because the countDown () method is called, The await method will be blocked until the current count reaches zero. Then, all the waiting threads will be released, and all subsequent calls of await will be returned immediately. This occurs only once-The Count cannot be reset. To reset the count, consider using javasicbarrier. The following example provides common locking usage. TestHarness creates a certain number of threads and uses them to concurrently execute specified tasks. It uses two locking methods, indicates "Start door" and "End Door" respectively ". The first thing each thread needs to do is wait on the startup door to ensure that all threads are ready before execution starts, the last thing that each thread needs to do is to reduce the countDown method of the call termination gate by 1, which enables the main thread to efficiently wait until all worker threads have completed execution, therefore, we can calculate the time consumed: public class TestHarness {public long timeTasks (int nThreads, final Runnable task) throws InterruptedException {final CountDownLatch startGate = new CountDownLatch (1 ); final CountDownLatch endGate = new CountDownLatch (nThreads); for (int I = 0; I <nThreads; I ++) {Thread t = new Thread () {Public void run () {try {startGate. await (); try {task. run ();} finally {endGate. countDown () ;}} catch (InterruptedException ignored) {}}; t. start ();} long start = System. nanoTime (); startGate. countDown (); endGate. await (); long end = System. nanoTime (); return end-start;} 2.2. FutureTask indicates the asynchronous computing that can be canceled. This class provides the basic implementation of Future by using the calculation method of starting and canceling the calculation, querying whether the calculation is complete, and obtaining the calculation result. Results can be obtained only when the calculation is complete. If the calculation is not complete, the get method is blocked. Once the calculation is complete, you cannot start or cancel the calculation again. The FutureTask method is summarized as follows: boolean cancel (boolean mayInterruptIfRunning) attempts to cancel the execution of this task. Protected void done () when this task is switched to isDone (whether it is normal or canceled), the protected method is called. V get () throws InterruptedException, ExecutionException, if necessary, wait until the computation is complete and obtain the result. V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException. If necessary, wait for the result to be obtained after the time specified for the computing completion (if the result is available ). Boolean isCancelled () returns true if it is canceled before the task is completed normally. Boolean isDone () returns true if the task has been completed. Void run () is set as the result of its calculation unless the Future is canceled. Protected boolean runAndReset () executes the computation without setting the result, and then resets this Future to the initial state. If the computation encounters an exception or has been canceled, this operation fails. Protected void set (V v) sets the result to a given value unless this Future has been set or canceled. Protected void setException (Throwable t) unless this ure has been set or it has been canceled, it reports an ExecutionException and uses the given throwable as its cause. FutureTask can be used to represent some long-time computations that can be started before the calculation results are used. The following code is to simulate a high-end computing. We can call start () first () method, and then call get to obtain the result: public class Preloader {ProductInfo loadProductInfo () throws DataLoadException {return null ;} private final FutureTask <ProductInfo> future = new FutureTask <ProductInfo> (new Callable <ProductInfo> () {public ProductInfo call () throws DataLoadException {return loadProductInfo ();}}); private f Inal Thread thread = new Thread (future); public void start () {thread. start ();} public ProductInfo get () throws DataLoadException, InterruptedException {try {return future. get ();} catch (ExecutionException e) {Throwable cause = e. getCause (); if (cause instanceof DataLoadException) throw (DataLoadException) cause; else throw new RuntimeException (e);} interface ProductInfo {} class DataLoa DException extends Exception {} 2.3. In terms of semaphores concept, semaphores maintain a license set. If necessary, each acquire () will be blocked before the license is available, and then wait for the license to be obtained. Add a license for each release (), which may release a blocked recipient. However, if you do not use the actual license object, Semaphore only counts the available license numbers and takes corresponding actions. Semaphore is usually used to limit the number of threads that can access certain resources (physical or logical. For example, the following classes use semaphores to control access to the content Pool: class Pool {private static final int MAX_AVAILABLE = 100; private final Semaphore available = new Semaphore (MAX_AVAILABLE, true ); public Object getItem () throws InterruptedException {available. acquire (); return getNextAvailableItem ();} public void putItem (Object x) {if (markAsUnused (x) available. release ();} // Not a particle ly efficient data structure; just for demo p Rotected Object [] items =... whatever kinds of items being managed protected boolean [] used = new boolean [MAX_AVAILABLE]; protected synchronized Object getNextAvailableItem () {for (int I = 0; I <MAX_AVAILABLE; ++ I) {if (! Used [I]) {used [I] = true; return items [I] ;}} return null; // not reached} protected synchronized boolean markAsUnused (Object item) {for (int I = 0; I <MAX_AVAILABLE; ++ I) {if (item = items [I]) {if (used [I]) {used [I] = false; return true;} else return false;} before obtaining an item, each thread must obtain a license from the semaphore, this option can be used. After the thread ends, it returns the item to the pool and returns the license to the semaphore, allowing other threads to obtain the item. Note that the synchronization lock cannot be kept when acquire () is called, because this prevents the items from being returned to the pool. Semaphores encapsulate the required synchronization to restrict access to the pool, which is separated from the synchronization required to maintain the consistency of the pool. Initializes the semaphore to 1 so that it has only one available license during use, so that it can be used as a mutually exclusive lock. This is also known as a binary semaphore because it can only have one available license or zero available license. When using this method, the binary semaphore has a certain attribute (different from many Lock implementations), that is, the "Lock" can be released by the thread, rather than by the owner (because the semaphore has no ownership concept ). This can be useful in some specialized contexts (such as deadlock recovery. The construction method of Semaphore optional accepts a fair parameter. When set to false, this class does not guarantee the order in which the thread obtains the license. In particular, intrusion is allowed, that is, you can assign a license to the thread that calls acquire () before the waiting thread. Logically, that is, the new thread places itself in the header of the waiting thread queue. When fairness is set to true, semaphores ensure that all threads that call methods to obtain methods follow the order in which they call these methods (that is, first-in-first-out; FIFO) to select a thread and obtain a license. Note that FIFO sorting must be applied to the specified internal execution points in these methods. Therefore, a thread may have called acquire before another thread, but it has reached the sorting point after the thread, and it is similar when returning from the method. Note that the non-synchronous tryAcquire method does not use fair settings, but uses any available licenses. Generally, semaphores used to control resource access should be initialized fairly to ensure that all threads can access resources. When semaphores are used for synchronization control of other types, the throughput advantage of unfair sorting is usually more important than fair considerations. Semaphore also provides convenient methods to simultaneously acquire and release multiple licenses. Be careful. Using these methods when fairness is not set to true increases the risk of uncertain delays. Memory consistency effect: the action happen-before calling the "release" method (for example, release () in the thread is followed by the successful "get" method (for example, acquire ()). 2.4 fence javasicbarrier is a synchronization helper class that allows a group of threads to wait for each other until it reaches a public barrier point. In a program involving a set of fixed threads, these threads must wait for each other from time to time. In this case, javasicbarrier is useful. This barrier can be reused after the waiting thread is released, so it is called a circular barrier. Javasicbarrier supports an optional Runnable command. After the last thread in a group of threads arrives (but before all threads are released), the command runs only once at each barrier point. This barrier operation is useful if the sharing status is updated before all participating threads continue. Example usage: The following is an example of barrier used in parallel decomposition design: class Solver {final int N; final float [] [] data; final CyclicBarrier barrier; class Worker implements Runnable {int myRow; Worker (int row) {myRow = row;} public void run () {while (! Done () {processRow (myRow); try {barrier. await () ;}catch (InterruptedException ex) {return ;}catch (BrokenBarrierException ex) {return ;}} public Solver (float [] [] matrix) {data = matrix; N = matrix. length; barrier = new CyclicBarrier (N, new Runnable () {public void run () {// mergeRows (...);}}); for (int I = 0; I <N; ++ I) new Thread (new Worker (I )). start (); waitUntilDone () ;}} in this example Worker threads process a row in the Matrix. Before processing all rows, the thread will wait at the barrier. After all rows are processed, the provided Runnable barrier operations are performed and merged. If the merge operator determines that a solution has been found, done () returns true and all worker threads terminate. If the barrier operation does not depend on the pending thread during execution, any thread in the thread group can execute this operation when it is released. To facilitate this operation, every call to await () will return the index of the thread that can reach the barrier. Then, you can select the thread to perform the barrier operation. for failed synchronization attempts, javasicbarrier uses a destroy mode of either all or all (all-or-none): if the cause is interrupted, failed, or timed out, as a result, the thread leaves the barrier point too early, so all other threads waiting at the barrierpoint will also exit in an abnormal way through BrokenBarrierException. Memory consistency effect: operations before await () called in the thread happen-before are part of the Barrier operation, the latter, in turn, happen-before follows the operation that is returned successfully in the corresponding await () from another thread.

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.