Synchronized statements and individual unsynchronized methods

In the Java documentation on the Internet, I found the following example:

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

They declare:

Without synchronized statements, there should be a separate, unsynchronized method for the sole purpose of calling nameList.add .

Does anyone understand what they mean?

The source can be found here .

+4
source share
3 answers

Initially, the article introduces synchronized methods - therefore, up to this point, the reader may believe that the unit of synchronization granularity is the only method.

Indeed, if there are no synchronized blocks / operators, the above example can only be performed as:

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

Thus, synchronized statements mean that you can save related code that needs to be synchronized internally. Instead of declaring a separate method that both pollutes the namespace, it also fragmentes the code stream. (Well, factoring methods are good in moderation, but it's better to have a choice.)

+5
source

This means that a piece of code 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. since synchronized(this) same as the synchronized(this) instance method (non-static), the code in the synchronized block can be ported to the synchronized method and called from the unsynchronized method. The effect will be the same.

+4
source

He tries to describe the need for Synchronized statements compared to Synchronized methods .

If you want to synchronize the update of lastName and nameCount , but not nameList.add() , then Synchronized operators are better. Otherwise, you will create one synchronized method to update lastName and nameCount and another unsynchronized method to add the name to the list.

I hope he clarifies.

+2
source

Source: https://habr.com/ru/post/1486867/


All Articles