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

本秂侑毒 提交于 2019-12-18 12:43:55

问题


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?


回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/7971946/in-java-return-value-within-synchronized-block-seems-like-bad-style-does-it-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!