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++;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With