All Articles

atomic switch

If you need to enter a section once atomically, do use one of the atomics as a switch:

if (state.compareAndSet(oldState, newState)) {
  // do this for first thread only once 
}

If you have additional conditions though, beware of the visibility of your other conditions, your switch alone will not guarantee correct behaviour if checking on mutable shared state. You may want to use a volatile or another thread-safe construct there, depending on your needs. For example, if you want to transition state once, but only within an “unlocked” window:

private volatile Locked locked = null;

if (locked == null && state.compareAndSet(oldState, newState)) {
  // do this once while unlocked 
}