幂等方法的含义是什么,以及在调用java.lang.AutoCloseable的close方法时有什么副作用? [英] What does idempotent method mean and what are the side effects in case of calling close method of java.lang.AutoCloseable?

查看:166
本文介绍了幂等方法的含义是什么,以及在调用java.lang.AutoCloseable的close方法时有什么副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.lang.AutoCloseable的close()方法的Java文档说

Java docs of close() method of java.lang.AutoCloseable says

 * <p>Note that unlike the {@link java.io.Closeable#close close}
 * method of {@link java.io.Closeable}, this {@code close} method
 * is <em>not</em> required to be idempotent.  In other words,
 * calling this {@code close} method more than once may have some
 * visible side effect, unlike {@code Closeable.close} which is
 * required to have no effect if called more than once.

幂等方法的含义是什么,以及两次调用此close()方法的副作用是什么?并且由于接口Closeable扩展了AutoCloseable,为什么在Closeable接口结束时不能看到副作用?

What do they mean by idempotent method and what are the side effects of calling this close() method twice? And since interface Closeable extends AutoCloseable why are the side effects not to be seen in the close of Closeable interface?

推荐答案

幂等意味着您可以多次应用该操作,但是一次调用的结果状态将与多次调用的结果状态无法区分。简而言之,多次调用该方法是安全的。实际上,第二个和第三个(等等)调用对程序的状态没有明显的影响。

Idempotent means that you can apply the operation a number of times, but the resulting state of one call will be indistinguishable from the resulting state of multiple calls. In short, it is safe to call the method multiple times. Effectively the second and third (and so on) calls will have no visible effect on the state of the program.

因此,如果你关闭这个对象一次,它就会关闭,你没有足够的信息来知道它是否是幂等的。但是,如果你关闭它两次,并且它第一次关闭,但第二次它抛出一个异常,它显然不是幂等的。另一方面,如果你关闭它一次,然后关闭它两次,第二次闭合导致项目以相同的方式保持关闭(也许它是一个noop),那么它是幂等的。

So if you close this object once, and it closes, you don't have enough information to know if it is idempotent. However, if you close it twice, and the first time it closes, but the second time it throws an exception, it is clearly not idempotent. On the other hand, if you close it once, and close it twice, and the second closure results in the item remaining closed in the same manner (perhaps it is a noop), then it is idempotent.

制作幂等可关闭的一种方法可能是:

One technique of making an idempotent Closeable could be:

public class Example implements Closeable {

  private boolean closed;

  public Example() {
    closed = false;
  }

  public void close() {
    if (!isClosed()) {
      closed = true;
    }
  }

  public boolean isClosed() {
    return closed;
  }
}

现在很明显,如果 close()被调用一次或多次,所有状态的返回通过 isClosed()将永远返回true。因此,方法 close()将被视为幂等。

Where it is now obvious that if close() is called once or multiple times, all returns of the state through isClosed() will forever return true. Therefore, the method close() would be considered idempotent.

这篇关于幂等方法的含义是什么,以及在调用java.lang.AutoCloseable的close方法时有什么副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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