Original link: http://coolxing.iteye.com/blog/1236909
Two types of mutex mechanisms:
1, synchronized
2, Reentrantlock
Reentrantlock is a new feature of Jdk5, the use of Reentrantlock can completely replace the replacement synchronized traditional locking mechanism, and the use of Reentrantlock way more object-oriented, but also more flexible, Online there are a lot of comparison between the two lock way article, here is not more words, we Baidu, Google a little to the bottom of the story. In this blog also wrote about the two types of lock implementation of the classic example of "producer consumers."
Synchronized way: Java threading: Three ways to implement producer consumer issues _1
Reentranlock Way: Java threading: Three ways to implement producer consumer issues _2
With regard to read and write locks, the interpretation of the language is not as straightforward as the code interpretation, the following two examples of reading and writing locks and read-write lock use:
Example 1:
[Java]View Plaincopy
- Import Java.util.HashMap;
- Import Java.util.Map;
- Import Java.util.concurrent.locks.ReadWriteLock;
- Import Java.util.concurrent.locks.ReentrantReadWriteLock;
- /**
- * @author amber2012
- *
- * Read/write Lock: Readwritelock
- *
- * In multi-threaded environment, the same data to read and write, will involve thread safety issues. For example, when one thread reads the data, another thread
- * Write data, resulting in inconsistent data; When a thread writes data, another thread is writing, and the data that is seen before and after the thread
- Inconsistency
- *
- * In this case, you can add a mutex in the read-write method, at any time can only allow one thread of a read or write operation, and not allow other threads to read or write operations, which
- * Sample can solve such problems, but the efficiency is greatly reduced. Because in a real business scenario, the number of times the data is read is usually high
- * In the operation of writing data, while the thread-to-thread read operation is not related to thread safety issues, there is no need to join the mutex, as long as the read-write, write-write period
- * It's OK to lock the room.
- *
- * For this case, read/write lock is the best solution!
- *
- * Mechanism for reading and writing locks:
- * "Read-read" is not mutually exclusive
- * "Read-write" mutex
- * "Write-write" mutex
- *
- * i.e. at all times must be guaranteed:
- * Only one thread is written;
- * When the thread is reading, the write operation waits;
- * When the thread is writing, the other thread writes and reads the operation to wait;
- *
- * The following is a cache class: an operation to demonstrate a read-write lock: Re-entry, demotion
- */
- Public class Cacheddata {
- //The cache should be single-case, where a singleton pattern is designed:
- private static Cacheddata Cacheddata = new Cacheddata ();
- Private Final Readwritelock lock = new Reentrantreadwritelock (); Read/write lock
- private map<string, object> cache = new hashmap<string, object> (); Cache
- Private Cacheddata () {
- }
- public static Cacheddata getinstance () {
- return cacheddata;
- }
- //Read cache:
- Public Object Read (String key) {
- Lock.readlock (). Lock ();
- Object obj = null;
- try {
- obj = Cache.get (key);
- if (obj = = null) {
- Lock.readlock (). Unlock ();
- //In this case, other threads are likely to get to the lock
- Lock.writelock (). Lock ();
- try {
- if (obj = = null) {
- obj = "Find database"; //The actual action is to find the database
- //Update the data to the cache:
- Cache.put (key, obj);
- }
- } finally {
- //When the front thread acquires a write lock, it can get to the read lock, which is called the re-entry of the lock, and then causes the downgrade of the write lock, called the downgrade lock.
- //The write lock can be degraded with re-entry, but only after all the write locks held by the current thread have been freed to allow the re-entry to reader to use
- //They. So in the process of re-entry, other threads will not have the opportunity to acquire a lock (the benefit of doing so). Just think, release the write lock,
- //Read lock, what is the disadvantage of doing this? If you do this, you may be interrupted by another thread after you release the write lock, before you get the read lock.
- //Re-entry ———— > Downgrade lock: Get the Write lock first, then fetch the read lock, and finally release the write lock (emphasis)
- Lock.readlock (). Lock ();
- Lock.writelock (). Unlock ();
- }
- }
- } finally {
- Lock.readlock (). Unlock ();
- }
- return obj;
- }
- }
Example 2:
[Java]View Plaincopy
- Import Java.util.Map;
- Import Java.util.TreeMap;
- Import Java.util.concurrent.locks.Lock;
- Import Java.util.concurrent.locks.ReadWriteLock;
- Import Java.util.concurrent.locks.ReentrantReadWriteLock;
- Import Javax.xml.crypto.Data;
- /**
- * @author amber2012
- *
- * A good example of the use of the Reentrantreadwritelock class in the JDK documentation, the following is a detailed description:
- *
- * When using certain kinds of Collection, you can use Reentrantreadwritelock to improve concurrency. Typically, the expected collection
- * Very large, the reader thread accesses it more often than the writer thread, and the cost of the entail operation is higher than the synchronization overhead, which is worth a try. For example, the following
- * is a class that uses TREEMAP, which is expected to be large and accessible at the same time.
- */
- Public class Rwdictionary {
- Private final map<string, data> Map = new treemap<string, data> ();
- Private final Readwritelock rwl = new Reentrantreadwritelock ();
- Private final Lock Readlock = Rwl.readlock ();
- Private final Lock Writelock = Rwl.writelock ();
- Public Data Get (String key) {
- Readlock.lock ();
- try {
- return Map.get (key);
- } finally {
- Readlock.unlock ();
- }
- }
- Public string[] AllKeys () {
- Readlock.lock ();
- try {
- return (string[]) Map.keyset (). ToArray ();
- } finally {
- Readlock.unlock ();
- }
- }
- Public Data put (String key, data value) {
- Writelock.lock ();
- try {
- return Map.put (key, value);
- } finally {
- Writelock.unlock ();
- }
- }
- public void Clear () {
- Writelock.lock ();
- try {
- Map.clear ();
- } finally {
- Writelock.unlock ();
- }
- }
- }
Forwarding: Java Threads: mutexes and read-write locks