实例级别我注意到下面的一段代码:同步在Java中
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
是毫无意义?毕竟它是同步的,那么为什么它是if (executed) throw new IllegalStateException("Already executed.");
?
实例级别我注意到下面的一段代码:同步在Java中
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
是毫无意义?毕竟它是同步的,那么为什么它是if (executed) throw new IllegalStateException("Already executed.");
?
我注意到下面的一段代码......它没有意义吗?
取决于上下文,但在面值上,代码做了一个非常特定和有用的事情。所以(呃)我猜是满分。
该代码可确保块以下的代码仅执行一次。这显然是在一个多线程应用程序中。你可以说,所有你需要的,这是当然的AtomicBoolean
:
private final AtomicBoolean executed = new AtomicBoolean();
...
// make sure that this is only executed once
if (!executed.compareAndSet(false, true)) {
throw new IllegalStateException("Already executed.");
}
上面的代码删除了块的需要,但代码的效果是一样的。我也可能会争辩说,代码应该返回某种错误代码而不是抛出,但这是一个实现特定的细节。
希望这会有所帮助。
'execution'的范围和生命周期是什么?这是这里的重要信息。 – NPE
http://stackoverflow.com/questions/13356702/how-can-i-make-sure-a-method-is-only-called-once-by-multiple-threads –