In java, the return value in the synchronized block seems to be bad. Does it really matter?

I have Collections.synchronizedList of WeakReference, _components;

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

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

But the compiler is completely satisfied. Note that List.add () returns TRUE. So normal, any exit from the synchronized block releases the lock, but isn't this LOOK strange? This is like a “hole” in a block, similar to using return in a loop.

Would you be happy to support such code?

+43
synchronized-block
Nov 01 '11 at 19:44
source share
2 answers

This is absolutely normal - as returned from a loop or from a try block that has a corresponding finally block. You just need to know the semantics, and at that moment it makes sense.

This is, of course, simpler code than introducing a local variable into 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; } 
+49
Nov 01 '11 at 19:48
source share

There is nothing wrong with returning inside a synchronized block. The lock will be released correctly.

+37
Nov 01 2018-11-11T00:
source share



All Articles