Understanding Java's synchronized keyword from a distributed lock perspective

Source: Internet
Author: User
Tags instance method zookeeper ticket

Distributed locks

Distributed lock as an zookeeper example, zookeeper is a coordinator of a distributed system, which we understand as a file system that can zookeeper create or delete folders or files on the server. Set D as a data system with no transaction capability, In the concurrency state, it is possible to read and write to individual data simultaneously. The client, a, is the client provided by Data System D, capable of reading and writing.

Several key roles have come into play, D is a data system that does not provide transactional behavior, its stored data can be read and written, in a single-client condition can guarantee the reliability of the data, but in two clients may be a concurrent request becomes unreliable, a write data may be covered by B, b read the data may be a not finished data. We can consider distributed locks without modifying the D source to provide atomic operations.

Client's originalAPI

void write(){    // 写数据}void read(){    // 读数据}

How to do it, the core is to be the zookeeper medium.

Modify the Client API, if read or write, we first want to zookeeper create a folder on, if the creation is successful, we do read and write operations, if not successful (on behalf of someone already created) we have been trying to create, until the creation of success. Read and write the data of D system when creation is successful. When you are finished, delete the zookeeper folder you created and exit the read-write method.

void write(){ while(在zookeeper上创建文件夹) {     写操作;     删除zookeeper的刚创建的文件夹;     return; }   }

This completes the synchronization of a distributed concurrency behavior. Assume that a has created a folder, B has no way to follow, will always try to create a folder, a after the operation to delete the folder, B has the opportunity to do the operation on the D system. This example produces a critical resource: D system data, and a race condition: A and B are concurrently read and write. ( zookeeper in fact, you can send a file for listeners, such as I create a folder is not successful, can listen to the folder, when the folder changes will notify you, then you can try to create a folder again (much like wait and notify), But in order not to focus on the zookeeper is not changed to monitor mode)

Synchronized keywords in Java

So let's go back to Java the synchronized key words, if you don't understand the above behavior and synchronized the relationship you can continue to look backwards.

synchronizedWhat exactly is locked, locked is a piece of memory, we set a value of 0 in the memory, when the value is 0 o'clock, a thread in order to modify the critical resource set it to 1, and then read and write operations, read and writes are set to 0, the other thread can change it to 1, read and write, and then set it to 0 ...... This memory is stored in the object header of each object, we call it the lock flag bit (actually the flag bit is not simple 0 and 1, the lock marker bit is divided into four states: no lock, biased lock, lightweight lock, and heavy lock, concurrency also involves lock escalation, etc., but this article does not do scrutiny, interested readers can consult relevant information).

When entering a synchronized code block or method, you will "create a folder" like the distributed lock described above, other threads cannot "create a folder" and will always try to "delete the folder" when the code block or method ends, and other threads can rob the opportunity to create the folder. synchronized Can be seen as a door, locked objects can be regarded as tickets. Do not think that the synchronized lock is a critical resource, synchronized is the lock symbol of an object as a ticket to constrain the behavior between competing threads: I only have one ticket, I only give one person.

To take synchronized a look at the usage, the race behavior between multiple threads must be constrained by the same ticket.

// 这锁住的是class Foo{    // 这锁住的是类对象    static synchronized void bar();    // 这锁住的是this,即实例对象    synchronized void bar();    // 等价于static synchronized    void bar(){        synchronized(Foo.class){};    }    // 等价于synchronized实例方法    void bar(){        synchronized(this){}    }}

For static methods you need to be aware of a point (if you want to observe the change of the biased lock), the instance method can directly observe the lock flag bit on the object header of the instance object, but the static method needs to observe the lock flag bit of the Foo.class object, if the lock flag bit of the observing instance object Bamboo Basket yo.

Understanding Java's synchronized keyword from a distributed lock perspective

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.