Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, return value within synchronized block seems like bad style. Does it really matter?

I have a Collections.synchronizedList of WeakReference, _components;

I wrote something like the following, expecting the complier to complain:

public boolean addComponent2(Component e) {     synchronized (_components) {         return _components.add(new WeakReference<Component>(e));     }         } 

But the compiler is perfectly satisfied. Note that List.add() returns TRUE. So ok, any exit from a synchronized block releases the lock, but doesn't this LOOK strange? It's kind of like a "hole" in the block, similar to using return in a loop.

Would you be happy maintaining code like this?

like image 539
Charlweed Avatar asked Nov 01 '11 19:11

Charlweed


People also ask

Why is synchronized in Java bad?

Some of the given reasons are: some evil code may steal your lock (very popular this one, also has an "accidentally" variant) all synchronized methods within the same class use the exact same lock, which reduces throughput. you are (unnecessarily) exposing too much information.

What is the disadvantage of synchronization in Java?

In simple two lines Disadvantage of synchronized methods in Java : Increase the waiting time of the thread. Create performance problem.

Is it better to make whole method synchronized or only critical section synchronized?

To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste. More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.

Which is more efficient synchronized method or synchronized block?

From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it. However the practical difference between synchronizing a method vs. a code block really depends on the method and what code is being left out of the synchronized block.


1 Answers

It's absolutely fine - as is returning from a loop, or from a try block which has an appropriate finally block. You just need to be aware of the semantics, at which point it makes perfect sense.

It's certainly simpler code than introducing a local variable for the sake of it:

// Ick - method body is now more complicated, with no benefit public boolean addComponent2(Component e) {     boolean ret;     synchronized (_components) {         ret = _components.add(new WeakReference<Component>(e));     }     return ret; } 
like image 97
Jon Skeet Avatar answered Sep 25 '22 17:09

Jon Skeet