简体   繁体   中英

Synchronized statements and separate unsynchronized methods

On the Java documentation online I found the following example:

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

They state:

Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add .

Does someone understand what they mean?

The source can be found here .

The article first introduces synchronized methods - so up to this point, the reader may believe that the unit of granularity of synchronization is a single method.

And indeed, if synchronized blocks/statements didn't exist, the example above could only be accomplished as:

public void addName(String name) {
    doSyncAdd(name);
    nameList.add(name);
}

private synchronized void doSyncAdd(String name) {
    lastName = name;
    nameCount++;
}

So, synchronized statements mean you can keep related code that needs to be synchronized inline. Rather than having to declare a separate method, which both pollutes the namespace and fragments the flow of the code. (Well, factoring out methods is good in moderation but it's nicer to have the choice.)

It means that your code snippet can be rewritten as

public void addName(String name) {
    setName(name)
    nameList.add(name);
}

private synchronized void setName(String name) {
    lastName = name;
    nameCount++;
}

ie as synchronized(this) is the same as a synchronized instance (non-static) method the code in the synchronized block can be moved to a synchronized method and called from the unsynchronized method. The effect will be the same.

It's trying to depict the need of Synchronized statements compared to Synchronized methods .

If you want to have synchronized updation of lastName and nameCount but not the nameList.add() then Synchronized statements is better option. Otherwise you would end up creating one synchronized method to update lastName and nameCount and another unsynchronized method to add the name in the list.

Hope it clarifies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM