Java docs of close() method of java.lang.AutoCloseable says
Note that unlike the
close()
method of Closeable, thisclose()
method is not required to be idempotent. In other words, calling this close method more than once may have some visible side effect, unlikeCloseable#close()
which is required to have no effect if called more than once. However, implementers of this interface are strongly encouraged to make their close methods idempotent.
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?
Advertisement
Answer
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.