Forwarding: Java Threads: mutexes and read-write locks

Source: Internet
Author: User
Tags mutex

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
  1. Import Java.util.HashMap;
  2. Import Java.util.Map;
  3. Import Java.util.concurrent.locks.ReadWriteLock;
  4. Import Java.util.concurrent.locks.ReentrantReadWriteLock;
  5. /**
  6. * @author amber2012
  7. *
  8. * Read/write Lock: Readwritelock
  9. *
  10. * 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
  11. * 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
  12. Inconsistency
  13. *
  14. * 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
  15. * 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
  16. * 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
  17. * It's OK to lock the room.
  18. *
  19. * For this case, read/write lock is the best solution!
  20. *
  21. * Mechanism for reading and writing locks:
  22. * "Read-read" is not mutually exclusive
  23. * "Read-write" mutex
  24. * "Write-write" mutex
  25. *
  26. * i.e. at all times must be guaranteed:
  27. * Only one thread is written;
  28. * When the thread is reading, the write operation waits;
  29. * When the thread is writing, the other thread writes and reads the operation to wait;
  30. *
  31. * The following is a cache class: an operation to demonstrate a read-write lock: Re-entry, demotion
  32. */
  33. Public class Cacheddata {
  34. //The cache should be single-case, where a singleton pattern is designed:
  35. private static Cacheddata Cacheddata = new Cacheddata ();
  36. Private Final Readwritelock lock = new Reentrantreadwritelock (); Read/write lock
  37. private map<string, object> cache = new hashmap<string, object> (); Cache
  38. Private Cacheddata () {
  39. }
  40. public static Cacheddata getinstance () {
  41. return cacheddata;
  42. }
  43. //Read cache:
  44. Public Object Read (String key) {
  45. Lock.readlock (). Lock ();
  46. Object obj = null;
  47. try {
  48. obj = Cache.get (key);
  49. if (obj = = null) {
  50. Lock.readlock (). Unlock ();
  51. //In this case, other threads are likely to get to the lock
  52. Lock.writelock (). Lock ();
  53. try {
  54. if (obj = = null) {
  55. obj = "Find database"; //The actual action is to find the database
  56. //Update the data to the cache:
  57. Cache.put (key, obj);
  58. }
  59. } finally {
  60. //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.
  61. //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
  62. //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,
  63. //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.
  64. //Re-entry ———— > Downgrade lock: Get the Write lock first, then fetch the read lock, and finally release the write lock (emphasis)
  65. Lock.readlock (). Lock ();
  66. Lock.writelock (). Unlock ();
  67. }
  68. }
  69. } finally {
  70. Lock.readlock (). Unlock ();
  71. }
  72. return obj;
  73. }
  74. }


Example 2:

[Java]View Plaincopy
    1. Import Java.util.Map;
    2. Import Java.util.TreeMap;
    3. Import Java.util.concurrent.locks.Lock;
    4. Import Java.util.concurrent.locks.ReadWriteLock;
    5. Import Java.util.concurrent.locks.ReentrantReadWriteLock;
    6. Import Javax.xml.crypto.Data;
    7. /**
    8. * @author amber2012
    9. *
    10. * A good example of the use of the Reentrantreadwritelock class in the JDK documentation, the following is a detailed description:
    11. *
    12. * When using certain kinds of Collection, you can use Reentrantreadwritelock to improve concurrency. Typically, the expected collection
    13. * 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
    14. * is a class that uses TREEMAP, which is expected to be large and accessible at the same time.
    15. */
    16. Public class Rwdictionary {
    17. Private final map<string, data> Map = new treemap<string, data> ();
    18. Private final Readwritelock rwl = new Reentrantreadwritelock ();
    19. Private final Lock Readlock = Rwl.readlock ();
    20. Private final Lock Writelock = Rwl.writelock ();
    21. Public Data Get (String key) {
    22. Readlock.lock ();
    23. try {
    24. return Map.get (key);
    25. } finally {
    26. Readlock.unlock ();
    27. }
    28. }
    29. Public string[] AllKeys () {
    30. Readlock.lock ();
    31. try {
    32. return (string[]) Map.keyset (). ToArray ();
    33. } finally {
    34. Readlock.unlock ();
    35. }
    36. }
    37. Public Data put (String key, data value) {
    38. Writelock.lock ();
    39. try {
    40. return Map.put (key, value);
    41. } finally {
    42. Writelock.unlock ();
    43. }
    44. }
    45. public void Clear () {
    46. Writelock.lock ();
    47. try {
    48. Map.clear ();
    49. } finally {
    50. Writelock.unlock ();
    51. }
    52. }
    53. }

Forwarding: Java Threads: mutexes and read-write locks

Related Article

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.