Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 719
user1883212 Avatar asked Jun 18 '13 15:06

user1883212


2 Answers

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.)

like image 159
Andrzej Doyle Avatar answered Sep 24 '22 20:09

Andrzej Doyle


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++;
}

i.e. 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.

like image 23
Boris the Spider Avatar answered Sep 24 '22 20:09

Boris the Spider