Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded correctness - Inconsistent synchronization

Whats wrong with this...?

public final void setListValid(final List<ValidRes> listValidRes) {
    this.listValidRes = listValidRes;
}

Sonar yells me at:

Inconsistent synchronization of xxx.listValidRes; locked 50% of time

Does anyone know what things i need to do ?

like image 696
Maulzey Avatar asked Dec 02 '22 23:12

Maulzey


1 Answers

The code given in the question has no synchronization. I assume that you synchronize on the this.listValidRes somewhere else in your code. And exactly that is what Sonar tells you: if you synchronize on a resource do so on all usages or don't do it at all and have someone else deal with it.

Basically it is a design decision:

  • You can chose to not synchronize and have the client bother with it. The advantage is that without synchronization it will be significantly faster. So if your class is used in a single-threaded setup, it will be better to ditch synchronization. But document it clearly to be not threadsafe or a client will use it multithreaded and complain about weird errors...

  • If you chose to (or have to) synchronize, then do it on every usage of the critical resource. There are different ways to achieve this. Maybe you want to show a usage of the resource that you in fact did synchronize. Maybe I or someone else can give you some good advice on that.

like image 69
Fildor Avatar answered Dec 14 '22 03:12

Fildor