Deep analysis of Java multithread synchronization lock mechanism and synchronized _java

Source: Internet
Author: User

For example, an object is like a big house, and the door opens forever. There are a lot of rooms in the house (ie method). These rooms have a locked (synchronized method) and are not locked (common method). A key was placed at the door of the room, and the key opened all the locked rooms. In addition, I compare all the threads that want to call the object method to the person who chengxiang into a room in the house. So much for everything, so let's look at how these things work.

Here we begin by clarifying our prerequisites. the object has at least one synchronized method, otherwise the key has no meaning. Of course, we will not have this subject.

A man wanted to enter a locked room, and he came to the door of the house and saw the key there (indicating that no one else had to use the locked room for the time being). So he went up to get the keys and used the rooms according to his plan. Note that he will return the key once every time he uses a locked room. even if he had to use two locked rooms in a row, he would return the keys in the middle.

Therefore, the general principle of the use of the key is: "With the use of borrowed, the use of that is also." ”

At this time other people can unrestricted use of those unlocked rooms, one can use one, two people can use a room, there is no limit. But if someone wants to go into a locked room, he's going to go to the gate and look at it. Have the key of course take to go, no words, can only wait.

If a lot of people are waiting for this key, who will give priority to the key when the key is returned? Not guaranteed. As in the previous example, the guy who wants to use two locked rooms in a row, if there are other people waiting for the key when the key is still in the middle, there is no guarantee that this guy will get it again. (The Java specification makes it clear in many places that it is not guaranteed that, like the Thread.Sleep (), how long it will return to run, the same priority thread is executed first, and that the number of threads in the waiting pool after the lock of the object is released is given priority, and so on.) I think the final decision is in the JVM, the reason is not guaranteed, because the JVM in making the decision, it is not simply based on a condition to make judgments, but according to a number of bars. But because the judgment condition is too many, if said that may affect the Java promotion, may also be because of the intellectual property protection reason. Sun gave a no guarantee and mixed it up. Understandable. But I believe these uncertainties are not entirely uncertain. Because the computer itself is running according to the instructions. Even seemingly random phenomena, in fact, there are rules to find. The computer has learned that the scientific name of random numbers in the computer is a pseudo random number, is the use of a certain method of writing out, looks random. In addition, perhaps because to make the determination too laborious, also does not have much significance, therefore is uncertain is uncertain. )

Let's take a look at the Sync code block. and synchronized methods are a little different.

1. In terms of size, the synchronized code block is smaller than the synchronization method. You can think of the sync code block as a space separated by a locked screen in a unlocked room.

2. The synchronized code block can also be artificially specified to obtain key for some other object. It's like specifying which key to use to unlock this screen, you can use the key of the room, you can also specify the key to another house to open, so you have to run to another house to bring the key, and the house with the key to open the house with the lock of the screen.

Remember that the key to the other house that you obtained does not affect others entering the room without locks.

Why should I use a synchronized code block? I think it should be like this: the first part of the synchronization of the program is very affecting the efficiency of the operation, and a method is usually to create some local variables, and then do some operations on these variables, such as operations, display and so on, and the more code covered by synchronization, the greater the impact on efficiency. So we usually try to narrow the scope of the impact. How to do it? Synchronize code blocks. We only synchronize where the synchronization is in one method, such as an operation.

In addition, the synchronization code block can specify the key the feature has an additional advantage, is the key that can occupy an object for a certain period of time. Do you remember the principle of using the key in general situation? It's not a normal situation now. The key you have achieved is not never return, but it is only when you exit the Sync code block.

and use the front guy who wants to use two locked rooms in a row for a metaphor. How to use the other one after using one of the rooms. Use the Sync code block. First create another thread, make a sync code block, and point the lock of that code block to the key of the house. And then start that thread. As long as you can catch the key to the house when you enter that code block, you can keep it until you exit that code block. That is to say, you can even go through all the locked rooms in the room, even sleep (10*60*1000), and the door has 1000 lines thread and so on this key. Very enjoyable.

Here is a talk about the relationship between sleep () method and key. When a thread gets the key and does not complete the synchronized content, if it is forced to sleep (), the key is still there. The key will not be returned until it is run again and all the synchronized content is finished. Remember, the guy just got tired of working and went to take a break, and he didn't finish what he was going to do. In order to avoid other people into the room to make a mess in the inside, even in bed when he would have to put the only key on the body.

Finally, one might ask, why should a key be opened, not a key, a door? I think it's purely a matter of complexity. A key a door is safer, but it involves a lot of problems. The creation, custody, acquisition, restitution, etc. of the key. Its complexity may increase exponentially with the increase of synchronization method, which seriously affects the efficiency. That's a trade-off. In order to add a little bit of security, resulting in a much lower efficiency, is how undesirable ah.

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.