Java synchronized keyword: synchronization mechanism Summary

Source: Internet
Author: User

In JAVA, the synchronized keyword can be used as a modifier of the function or as a statement in the function, that is, the synchronization method and synchronization statement block.

Figuring out which object synchronized is locked can help us design safer multi-threaded programs.

I used synchronization not long ago. Now I will go back and summarize the synchronization in JAVA to summarize the previous work and self-technical statements.

The synchronized keyword of JAVA can be used as the modifier of the function or as the statement in the function, that is, the synchronization method and synchronization statement block.

For further classification, synchronized can act on instance variables, object reference, static functions, and class literals (literal constants of class names.

Before proceeding, we need to clarify the following points:
A. no matter whether the synchronized keyword is added to the method or object, the lock he acquires is an object, instead of using a piece of code or function as a lock-and the synchronization method is likely to be accessed by objects in other threads.
B. Each object has only one lock associated with it.
C. Implementing synchronization requires a large amount of system overhead as a cost, and may even cause deadlocks. Avoid unnecessary synchronization control as much as possible.

Next we will discuss the impact of synchronized on code in different places:

Suppose P1 and P2 are different objects of the same class. This class defines synchronization blocks or Synchronization Methods in the following situations, and P1 and P2 can call them.

Java synchronized usage Summary

1. When synchronized is used as a function modifier, the sample code is as follows:

  1. Public synchronized void method (){
  2. //....
  3. }

This is the synchronization method. Which object is synchronized locked at this time? The lock is to call this synchronization method object. That is to say, when an object P1 executes this synchronization method in different threads, they form mutual exclusion to achieve synchronization. However, the other object P2 generated by the Class to which this object belongs can call the method with the synchronized keyword.
The above sample code is equivalent to the following code:

  1. Public void method ()
  2. {
  3. Synchronized (this) // (1)
  4. {
  5. //.....
  6. }
  7. }

(1) What does this mean? It refers to the object that calls this method, such as P1. It can be seen that the synchronization method essentially acts on the object reference.

-- The thread that obtains the P1 object lock can call the synchronization method of P1. For P2, the P1 lock has nothing to do with it,

In this case, the program may also get rid of the control of the synchronization mechanism, resulting in data confusion.

 

2. Synchronization block. The sample code is as follows:

  1. Public void method (SomeObject so ){
  2. Synchronized (so)
  3. {
  4. //.....
  5. }
  6. }

In this case, the lock is the so object. Whoever gets the lock can run the code that he controls. When a specific object is used as a lock, you can write a program in this way,

However, when there is no clear object as the lock and you just want to synchronize a piece of code, you can create a special instance variable (which must be an object) to act as the lock:

  1. Class Foo implements Runnable
  2. {
  3. Private byte [] lock = new byte [0]; // special instance variable
  4. Public void method ()
  5. {
  6. Synchronized (lock ){//... }
  7. }
  8. //.....
  9. }

Note: creating a zero-Length byte array object is more economical than any other object-view the compiled bytecode: only three operation codes are required for generating a zero-Length byte [] object,

Object lock = new Object () requires seven lines of operation code.

 

3. apply synchronized to the static function. The sample code is as follows:

  1. Class Foo
  2. {
  3. Public synchronized static void method1 () // synchronized static function
  4. {
  5. //....
  6. }
  7. Public void method2 ()
  8. {
  9. Synchronized (Foo. class) // class literal (class Name literal constant)
  10. }
  11. }

The method2 () 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 ).
I remember I saw in objective Java that the use of Foo. class and P1.getClass () for synchronization locks is not the same, and P1.getClass () cannot be used ()

To lock this Class. P1 refers to the object generated by the Foo class.
It can be inferred that A class defines A static function A of synchronized, and also defines the instance function B of synchronized,

When the same object Obj of this class accesses Methods A and B in multiple threads, the synchronization will not be formed because their locks are different. The lock of method A is the Class to which Obj belongs,

The lock of B is the object to which Obj belongs.

 

Java synchronized usage is summarized as follows:

Figuring out which object synchronized is locked can help us design safer multi-threaded programs.

There are also some tips to make our synchronized access to shared resources more secure:
1. Define the private instance variable + its get method, instead of the public/protected instance variable. If the variable is defined as public,

The object can directly obtain and change the object by bypassing the control of the synchronization method. This is also one of the standard implementations of JavaBean.
2. If the instance variable is an object, such as an array or an ArrayList, the above method is still insecure, because when the external object obtains this

When an instance object is referenced and directed to another object, the private variable changes. In this case, you need to set the get Method

In addition, synchronized synchronization is added, and only the clone () of the private object is returned. In this way, the caller obtains the reference of the object copy.

This article is from leo_faith's blog.

Http://developer.51cto.com/art/200908/143504.htm

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.