What does idempotent method mean and what are the side effects in case of calling close method of java.lang.AutoCloseable?

后端 未结 3 677
予麋鹿
予麋鹿 2020-12-08 02:50

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

Note that unlike the close() method of Closeable, this close() method is no

3条回答
  •  旧时难觅i
    2020-12-08 03:35

    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.

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

    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.

提交回复
热议问题