Synchronized for java concurrency

Source: Internet
Author: User

Synchronized for java concurrency

In Java, each object has a lock mark (monitor), also known as a monitor. When multiple threads access an object at the same time, the thread can only access the Lock of this object.

In Java, you can use the synchronized keyword to mark a method or code block. When a thread calls the synchronized Method of the object or accesses the synchronized code block, the thread obtains the lock of the object, other threads cannot access this method at the moment. This thread will release the Lock of this object only after the method is executed or the code block is executed. Other threads can execute this method or code block.

Note:

1) when a thread is accessing the synchronized Method of an object, other threads cannot access other synchronized methods of the object. This is simple because an object has only one lock. When a thread acquires the Lock of this object, other threads cannot obtain the Lock of this object, therefore, other synchronized methods of the object cannot be accessed.

2) When a thread is accessing the synchronized Method of an object, other threads can access the non-synchronized Method of the object. This is a simple reason. The non-synchronized method does not need to obtain the Lock of this object. If a method does not use the synchronized keyword to modify it, it does not use critical resources, other threads can access this method.

3) If thread A needs to access the synchronized Method fun1 of the object object1, and thread B needs to access the synchronized Method fun1 of the object object2, even if object1 and object2 are of the same type ), it does not cause thread security issues because they access different objects, so there is no mutex problem.

 

The synchronized code block is much more flexible than the synchronized method. Because only a part of the code in a method only needs to be synchronized. If synchronized is used to synchronize the entire method at this time, the execution efficiency of the program will be affected. The synchronized code block can be used to avoid this problem. The synchronized code block can be used to synchronize only the places to be synchronized. In addition, each class also has a lock that can be used to control concurrent access to static data members. If a thread executes the non-static synchronized Method of an object, the other thread needs to execute the static synchronized Method of the class to which the object belongs. In this case, no mutual exclusion occurs, the access to the static synchronized method occupies the class lock, while the access to the non-static synchronized method occupies the object lock, so there is no mutual exclusion.

 

[Java]View plaincopy
  1. PublicclassTest {
  2.  
  3. Publicstaticvoidmain (String [] args ){
  4. FinalInsertDatainsertData = newInsertData ();
  5. NewThread (){
  6. @ Override
  7. Publicvoidrun (){
  8. InsertData. insert ();
  9. }
  10. }. Start ();
  11. NewThread (){
  12. @ Override
  13. Publicvoidrun (){
  14. InsertData. insert1 ();
  15. }
  16. }. Start ();
  17. }
  18. }
  19.  
  20. ClassInsertData {
  21. Publicsynchronizedvoidinsert (){
  22. System. out. println ("execute insert ");
  23. Try {
  24. Thread. sleep (5000 );
  25. } Catch (InterruptedExceptione ){
  26. E. printStackTrace ();
  27. }
  28. System. out. println ("insert execution completed ");
  29. }
  30.  
  31. Publicsynchronizedstaticvoidinsert1 (){
  32. System. out. println ("execute insert1 ");
  33. System. out. println ("completed insert1 execution ");
  34. }
  35. } Result:

     

    Execute insert

    Execute insert1

    The execution of insert1 is complete.

    Insert execution completed

     

    The insert method is executed in the first thread, which does not block the insert1 method execution in the second thread.

    Next, let's take a look at what the synchronized keyword has done. Let's decompile its bytecode and look at it. The following code decompile the bytecode:

     

    [Java]View plaincopy
    1. PublicclassInsertData {
    2. PrivateObjectobject = newObject ();
    3.  
    4. Publicvoidinsert (Threadthread ){
    5. Synchronized (object ){
    6.  
    7. }
    8. }
    9.  
    10. Publicsynchronizedvoidinsert1 (Threadthread ){
    11.  
    12. }
    13.  
    14. Publicvoidinsert2 (Threadthread ){
    15.  
    16. }
}

[Java]View plaincopy
  1. ClassFooimplementsRunnable
  2. {
  3. Privatebyte [] lock = newbyte [0]; // special instance variable
  4. PublicvoidmethodA ()
  5. {
  6. Synchronized (lock ){//...}
  7. }
  8. //.....
} Apply synchronized to the static function. The sample code is as follows: [Java]View plaincopy
  1. ClassFoo
  2. {
  3. PublicsynchronizedstaticvoidmethodAAA () // synchronized static function
  4. {
  5. //....
  6. }
  7. PublicvoidmethodBBB ()
  8. {
  9. Synchronized (Foo. class) // classliteral (class Name literal constant)
  10. }
} The methodBBB () method in the Code uses class literal as the lock. It produces the same effect as the synchronized static function, and the obtained lock is very special, is the Class of the object currently calling this method (Class, instead of a specific object generated by this Class ).
Synchronized defects:
1) the thread that acquires the lock executes the code block and then releases the lock;
However, if the synchronized keyword is used for synchronization, a problem occurs:
 

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.