在java中,synchronized块中的返回值看起来像坏样式。真的有关系吗?

时间:2011-11-01 19:44:24

标签: synchronized-block

我有一个WeakReference的Collections.synchronizedList,_components;

我写了类似下面的内容,期望编辑抱怨:

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

但编译器非常满意。请注意,List.add()返回TRUE。好吧,从synchronized块的任何退出都会释放锁,但是这个LOOK不是很奇怪吗?它有点像块中的“洞”,类似于在循环中使用return。

您是否乐意维护这样的代码?

2 个答案:

答案 0 :(得分:56)

绝对没问题 - 从循环返回,或从具有适当try块的finally块返回。你只需要了解语义,这一点非常有意义。

它的代码肯定比为了它引入局部变量更简单:

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

答案 1 :(得分:44)

synchronized块内返回没有任何问题。锁定将被正确释放。