在Java中,同步块内的返回值似乎是错误的样式.真的有关系吗? [英] In java, return value within synchronized block seems like bad style. Does it really matter?

查看:74
本文介绍了在Java中,同步块内的返回值似乎是错误的样式.真的有关系吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是编译器非常满意.请注意,List.add()返回TRUE.好吧,同步块的任何退出都会释放该锁,但这看起来并不奇怪吗?就像在块中的一个洞",类似于在循环中使用return.

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?

推荐答案

这绝对好-就像从循环或具有适当finally块的try块返回的一样.您只需要了解语义,在这一点上它就很有意义.

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

这篇关于在Java中,同步块内的返回值似乎是错误的样式.真的有关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆