A brief talk on Java synchronization mechanism how does ――synchronized affect code?

Source: Internet
Author: User
Tags define array object key words variables reference variable thread
Java support for multithreading and synchronization mechanism by popular, it seems that the use of the Synchronized keyword can easily solve the problem of multithreading shared data synchronization. What's going on? --also have to synchronized the role of the key words to understand the conclusion. In general, the Synchronized keyword can be used as a modifier of a function, or as a statement within a function, which is usually a synchronized method and a block of synchronized statements. In the finer categories, synchronized can be used for instance variables, object reference (reference), static functions, and class literals (class name literal constants). Before we elaborate further, we need to be clear on A few points: A. Whether the Synchronized keyword is added to a method or an object, the lock it obtains is an object rather than a piece of code or function as a lock-and the synchronization method is likely to be accessed by objects of other threads. B Each object has only one lock (lock) associated with it. C To achieve synchronization is a very large system overhead as a cost, and may even cause deadlock, so try to avoid unnecessary synchronization control.

Next, discuss synchronized's impact on the code in different places:

Assuming that P1, P2 are different objects of the same class, this class defines synchronization blocks or synchronization methods that can be invoked by P1, P2, and so on. 1.   When synchronized is treated as a function modifier, the sample code is as follows: public synchronized void Methodaaa () {//...} This is the synchronization method, then which object synchronized lock? It locks a call to this synchronization method object. That is, when an object P1 the synchronization method in a different thread, they form a mutex that achieves the effect of synchronization. But another object generated by the class that this object belongs to P2 can invoke the method that was added to the Synchronized keyword arbitrarily. The example code above is equivalent to the following code: public void Methodaaa () {synchronized (this)      //  (1) {       /...}} What does this refer to at   (1)? It refers to the object that invokes this method, such as P1. The visible synchronization method is essentially a synchronized action on the object reference. -The thread that gets the lock on the P1 object can call the P1 synchronization method, and for P2, P1 This lock has nothing to do with it, and the program may get rid of the synchronization mechanism in this case, resulting in data chaos: 2. Sync block, sample code as follows:            public void method3 (Someobject so)                {                      synchronized (SO) {       /...}} Then the lock is the object of so, and whoever gets the lock can run the code it controls. When there is a MingA true object can be written as a lock, but when there is no clear object as a lock and just want to synchronize a piece of code, 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 Me ThodA () {       synchronized (lock) {//...}} .....} Note: A 0-length byte array object is created more economically than any object--view compiled bytecode: A 0-length byte[] object takes only 3 opcode, while object lock = new Object () requires 7 rows of opcode. 3. Synchronized action on the static function, the sample code is:      Class Foo {public synchronized static void Methodaaa ()   //synchronization of the static function {//....}public void methodbbb () {       synchronized ( Foo.class)   //  class literal (class name literal constant)}      }   The METHODBBB () method in the code is to use class literal as a lock, and it produces the same effect as the synchronized static function, and the lock is special, the class that the object that is currently calling the method belongs to (class, Instead of being a specific object generated by this class. Remember in the book "Effective Java" that the Foo.class and P1.getclass () used as a synchronous lock is not the same, can not use P1.getclass () to achieve the purpose of locking this class. P1 refers to objects that are generated by the Foo class.

It can be inferred that if a class has defined a synchronized static function A and also defines a synchronized instance function B, then the same object obj of this class will not constitute a synchronization when accessing A and B two methods, respectively, in multiple threads. Because their locks are not the same. The lock of a method is the object of obj, and the lock of B is the class that obj belongs to. The summary is as follows: figuring out which object the synchronized is locking can help us design more secure multithreaded programs.

There are also some techniques that will make it more secure to synchronize access to shared resources: 1. Define private instance variable + its get method instead of defining public/protected instance variables. If you define a variable as public, the object can get it directly and change it in the outside world 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 ArrayList, the above method is still unsafe, because when an external object gets a reference to the instance object through the Get method and points it to another object, the private variable is changed, It's dangerous. At this point, you need to synchronize the Get method with synchronized, and return only the Clone () of the private object-so that the caller gets a reference to the object's copy.



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.