Java thread synchronization mechanism synchronized keyword understanding

Source: Internet
Author: User

thread synchronization:

Because multiple threads of the same process share the same piece of storage space, it also poses a serious problem with access violations when it comes to convenience. The Java language provides a specialized mechanism to resolve this conflict, effectively avoiding the same data object being accessed by multiple threads concurrently.

a few questions need to be clarified:

1)The synchronized keyword can be used as a modifier of a function, or as a statement within a function, that is, a synchronous method and a synchronous statement block. In the case of finer classifications, synchronized can be used for instance variables, object reference, static functions, and class literals (literal constants of classes).
2) Regardless of whether the Synchronized keyword is added to a method or an object, the lock it obtains is an object, not a piece of code or function as a lock-and the synchronization method is likely to be accessed by other threads ' objects.
3) Each object has only one lock (lock) associated with it.
4) To achieve synchronization is a big cost of the system, and may even cause a deadlock, so try to avoid unnecessary synchronization control.

1, the scope of the SYNCHRONIZED keyword has two kinds:

1) is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, as long as one line Process accesses one of the synchronized methods, and other threads cannot access any of the synchronized methods in the object at the same time. At this point, the synchronized method of the different object instances is not interfering. In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;

2) is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class.


The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to execute, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released from the method return , the blocked thread can then get the lock and re-enter the executable state. This mechanism ensures that at the same time for each class instance, at most one of its member functions declared as synchronized is in an executable state (since at most one can obtain a lock corresponding to that class instance), it effectively avoids the access violation of the class member variable (as long as all possible access to the class member becomes Methods are declared as synchronized).
  
In Java, not only class instances, each class also corresponds to a lock, so we can also declare the static member function of the class as synchronized to control its access to static member variables of the class.
  
   defects of the Synchronized method :synchronous method, which object is synchronized locked at this time? It is locked by calling this synchronization method object. That is, when an object P1 the synchronization method in a different thread, it creates mutual exclusion between them and achieves the effect of synchronization. However, another object generated by the class that this object belongs to P2 can call this method of adding the Synchronized keyword arbitrarily .The method of synchronization is essentially the synchronized action on object reference. --the thread that got the P1 object lock can call P1 's synchronous method, and for P2, P1 This lock has nothing to do with it, and the program may get rid of the control of synchronization mechanism in this situation, causing data confusion: (, if declaring a large method as synchronized will greatly affect efficiency, typically, if the method run () of the thread class is declared as synchronized, it will cause it to be any synchronized to this class because it is running throughout its lifetime. The call to the method will never succeed. Of course we can put the code that accesses the class member variable into a specialized method, declare it as synchronized, and use it in the main method to solve the problem, but Java provides us with a better solution, that is, the synchronized block.


2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access. The usage is: synchronized (this) {/* chunk */}, which is scoped to the current object.


The lock is the object, and whoever gets the lock can run the code it controls. When there is a definite object as the lock, you can write the program, but when there is no explicit object as a lock, just want to let a piece of code synchronization, you can create a special instance variable (it has to be an object) to act as a lock:
class Foo implements Runnable
{
private byte[] lock = new byte[0];// Special instance variable
public void MethodA ()
{
Synchronized (lock) {//...}
}
//.....
}
Note: A 0-length byte array object will be more economical to create than any object-view compiled bytecode: generates a 0-length byte[] object with only 3 opcode, and object lock = new Object () requires 7 lines of opcode.


3. the synchronized action is applied to the static function , and the sample code is as follows:
Class Foo
{
Public synchronized static void Methodaaa () // synchronous static function
{
//....
}
Public void methodbbb ()
{
synchronized (foo.class)//class literal ( class name literal constant)
}    }
the METHODBBB () method in the code is the case of the class literal as a lock, which produces the same effect as the synchronous static function, and the resulting lock is very special, which is the class that the object that is currently calling this method belongs to (class, Instead of being a specific object produced by this class.


It can be inferred that if a synchronized static function A is defined in a class, and a synchronized instance function B is also defined, then the same object of this class, obj, accesses A and B two methods in multiple threads, which does not constitute synchronization. Because their locks are not the same. The lock of the B method is the Obj object, and the lock of B is the class that obj belongs to.


A more secure technique for synchronizing access to shared resources:


< /span>
        1)   defines the private instance variable + its Get method, rather than defining the public/ The instance variable of the protected. If a variable is defined as public, the object can get it directly from the outside world by bypassing the control of the synchronization method and altering it. This is also one of the standard implementations of JavaBean.
         2) If the instance variable is an object, such as an array or ArrayList, then the above method is still unsafe, Because when an outside object gets a reference to the instance object through a get method and points it to another object, then the private variable is changed, not dangerous. At this point, the Get method is added to the synchronized synchronization, and only the Clone () of the private object is returned-so that the caller gets a reference to the object copy.


Add :


The Synchronized keyword cannot be inherited, that is, the method of the base class synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method.



Java thread synchronization mechanism synchronized keyword understanding

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.