To guarantee idempotent close() operation in a Closeable class that could potentially be closed from multiple threads, I thought of using AtomicBoolean:
private AtomicBoolean closing = new AtomicBoolean(false);
@Override
public void close() {
if (!closing.getAndSet(true)) {
...do some non-idempotent operations...
}
}
Is this a correct way of doing it? I saw some uses of compareAndSet while searching. Which method should I use for this purpose - getAndSet or compareAndSet - and why?