Do not use both the Reentrantlock class and the Synchronized keyword to lock different methods for modifying the same resource

Source: Internet
Author: User

Transfer from http://agrael.iteye.com/blog/685840

This article is about the problem of using the Reentrantlock class with the Synchronized keyword, not the Reentrantlock class and the Synchronized keyword tutorial.
The Synchronized keyword is one of the most important keywords in Java multithreaded programming, and it maintains security in this thread concurrency. There are 2 ways to use synchronized generally.
Lock the current instance

Java code
  1. Use synchronized on methods to achieve locking effect
  2. Public synchronized void xxx () {
  3. //...  
  4. }
  5. Locks the specified instance by locking it to the desired effect
  6. Public void yyy () {
  7. synchronized (this) {
  8. //...  
  9. }
  10. }
  11. Public void zzz () {
  12. synchronized (xObject) {
  13. //...  
  14. }
  15. }


The first and second are those of the object instances to which the current method belongs, and the third is to lock the specified instance.
This article does not intend to explain in detail the Synchronized keyword, the detailed description of the synchronized please refer to other materials.


The lock framework in Java.util.concurrent.lock is an abstraction of locking, which allows the implementation of a lock to be implemented as a Java class, rather than as a language feature. Reentrantlock is an implementation of the lock interface that defines the reentrant lock. According to the API's description: "A reentrant mutex lock lock, which has the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and the statement, but is more powerful." "It can be found that the most basic function of Reentrantlock is to implement the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and the statement."
Reentrantlock provides a lot of methods, but here we only discuss how to implement synchronized the same functionality.
Examples used in the API are:

Java code
  1. Class X {
  2. Private Final Reentrantlock lock = new Reentrantlock ();
  3. // ...  
  4. public void M () {
  5. Lock.lock (); //block until condition holds
  6. try {
  7. //... method body
  8. } finally {
  9. Lock.unlock ()
  10. }
  11. }
  12. }


As you can see, if the above code is replaced with synchronized, it should be:

Java code
    1. Public synchronized void m () {
    2. //... method body
    3. }


Or

Java code
    1. Public void M () {
    2. synchronized (this) {
    3. //... method body
    4. }
    5. }


The current instance is locked. This is also the focus of this article. (For more information on Reentrantlock, please refer to other materials)
Since Reentrantlock and synchronized both provide the same behavior (no performance issues are discussed here), it is possible to use Reentrantlock and synchronized for threading concurrent programming in the process. They can all work very well, too. But what if you use them two at a time? What would be the result?
Look at the following code:

Java code
  1. Package cn.agrael.test.thread;
  2. Import Java.util.concurrent.locks.ReentrantLock;
  3. Public class Reentrantlockandsynchronized {
  4. Private Final Reentrantlock lock = new Reentrantlock ();
  5. Private volatile int i = 0;
  6. public void Lockadd () throws Exception {
  7. Lock.lock ();
  8. try {
  9. Check ("Lockadd");
  10. i++;
  11. i++;
  12. } finally {
  13. Lock.unlock ();
  14. }
  15. }
  16. public synchronized void Synchronizedadd () throws Exception {
  17. Check ("Synchronizedadd");
  18. i++;
  19. i++;
  20. }
  21. public void Synchronizedadd () throws Exception {
  22. Lock.lock ();
  23. try {
  24. Check ("Lockadd");
  25. i++;
  26. i++;
  27. } finally {
  28. Lock.unlock ();
  29. //      }
  30. //  }
  31. private void Check (String methodName) throws Exception {
  32. if (i% 2! = 0) {
  33. throw New Exception (MethodName + ":" + i);
  34. }
  35. }
  36. public static void Main (string[] args) throws Exception {
  37. final reentrantlockandsynchronized add = new reentrantlockandsynchronized ();
  38. Thread thread1 = new Thread (new Runnable () {
  39. public Void Run () {
  40. try {
  41. While (true) {
  42. Add.lockadd ();
  43. }
  44. } catch (Exception e) {
  45. E.printstacktrace ();
  46. System.exit (0);
  47. }
  48. }
  49. });
  50. Thread thread2 = new Thread (new Runnable () {
  51. public Void Run () {
  52. try {
  53. While (true) {
  54. Add.synchronizedadd ();
  55. }
  56. } catch (Exception e) {
  57. E.printstacktrace ();
  58. System.exit (0);
  59. }
  60. }
  61. });
  62. Thread1.start ();
  63. Thread2.start ();
  64. }
  65. }


There is an I variable of type int, and provides a Lockadd method using Reentrantlock locking and a Synchronizedadd method that uses synchronized locking, all 2 methods provide the same operation, first verifying whether I is an even number, Throws an exception if it is not, and provides 2 times i++ operation. Java i++ is not atomic operation, will involve reading and writing, and also provide 2 times i++, if so, there will be concurrency problems, so we provide reentrantlock and synchronized to lock, to ensure thread safety. If our ideas are workable, then I will always be read with even numbers, and we will never throw out the exceptions we specify. But the result is not so, after running for a while, throws an exception, proves that our idea failed. Because Reentrantlock and synchronized provide different mechanisms, they are relatively independent, which is equivalent to two locks, each locking their respective.
So in the end, we concluded that not using both the Reentrantlock class and the Synchronized keyword lock will modify different methods of the same resource.

Do not use both the Reentrantlock class and the Synchronized keyword to lock different methods for modifying the same resource

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.