Java Concurrent Programming Lock (the magic of the lock) __ programming

Source: Internet
Author: User
Tags mutex

Another mechanism for implementing thread synchronization or mutual exclusion in Java 5 is the use of lock. Lock is more object-oriented than the synchronized method in the traditional threading model.
Mutual-exclusion lock –lock (Reentrantlock)
A mutex is a lock that can be held by at most one thread at a time. Before jdk1.5, we usually use the synchronized mechanism to control the access of multiple threads to shared resources. Now, Lock provides a wider range of locking operations than the synchronized mechanism, the main differences between lock and synchronized mechanisms:
The synchronized mechanism provides access to an implicit monitor lock associated with each object and forces all lock acquisition and release to appear in a block structure, which must be released in reverse order when multiple locks are acquired. The synchronized mechanism is implicit in the release of the lock, and the lock is freed as long as the thread running code is outside the synchronized block range. The lock mechanism must explicitly invoke the Unlock () method of the lock object to release the lock, which provides the possibility of acquiring and releasing the lock not appearing in the same block structure, and releasing the lock in a more free order.

Read and Write lock –readwritelock (reentrantreadwritelock)
Read-write Lock: Reading lock and write lock, multiple read lock is not mutually exclusive, read lock and write lock mutually exclusive, write lock and write lock mutually exclusive. In other words, read locks allow multiple reader threads to hold simultaneously, while write locks can be held at most one writter thread.
Read-Write lock usage: The frequency of reading shared data is much greater than the frequency of modifying shared data, in these situations, using read-write locks to control access to shared resources, can improve concurrency performance.

Package com.huang.test;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.concurrent.locks.ReadWriteLock;

Import Java.util.concurrent.locks.ReentrantReadWriteLock; /** * Read and write lock of the magic * Simple Caching principle * * * @author Wuseyukui */public class Cachedemo {private Readwritelock lock = new Reent

    Rantreadwritelock ();

    Private map<string, object> cache = new hashmap<string, object> (); public static void Main (string[] args) {}/** * simple, Popular * Disadvantage: only when writing needs synchronization (mutual exclusion), multithreading reading data does not need synchronization, affect efficiency * @param key * @return//Public synchronized Object GetData (String key) {//Object obj = Cache.get (key
);
if (obj = = null) {//obj = "AAA";//is actually going to query db//}///return obj;
     /** * High efficiency, multithreading read data with read lock can be concurrent, write data with write lock mutex.
         * @param key * @return/public synchronized Object GetData (String key) {Lock.readlock (). Lock ();
         Object obj = null; try {oBJ = Cache.get (key);
                 if (obj = = null) {Lock.readlock (). Unlock (); Lock.writelock (). Lock ();//①try {//For the code is strictly prohibited careful//suppose there are three threads to the code ①
                     , thread 1 successfully acquired a write lock and another two threads were blocked.
                         When thread 1 executes to ②, the write lock is freed, and another two threads have the opportunity to acquire a write lock and perform DB operations, at which point obj is not empty and no more need to query db if (obj = null) { obj = "AAA";//is actually going to query db} catch (Exception e) {E.printstac
                Ktrace ();
             finally {Lock.writelock (). Unlock ();//②} lock.readlock (). Lock ();
        } catch (Exception e) {e.printstacktrace ();
        finally {Lock.readlock (). Unlock ();
    return obj;
 }

}

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.