0

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?

locke14
  • 1,335
  • 3
  • 15
  • 36
k314159
  • 5,051
  • 10
  • 32
  • 3
    I don't think that's correct. How about all the other methods? How are they made thread-safe? E.g. how do you prevent closing the object while it is in the middle of executing another method in different thread? Thread-safety applies to all the methods, and whatever mechanism you use applies to them all. – Andreas Oct 12 '20 at 15:04
  • You could perhaps build something using a CountDownLatch, similar to https://stackoverflow.com/questions/42047944/how-to-make-sure-that-method-is-executed-only-once-and-from-one-thread-only All other methods will then probably have to check your `closing`-boolean and fail (exception?) if it is true. – Hulk Oct 12 '20 at 15:15
  • 1
    In this case you can use either. See the linked question. In my personal opinion, using `compareAndSet(false, true)` makes your intent clearer. – dnault Oct 12 '20 at 17:02

0 Answers0