net.dongliu.commons.concurrent.Once Maven / Gradle / Ivy
package net.dongliu.commons.concurrent;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* Utils used to do something only once
*
* @author Liu Dong
*/
public class Once {
private volatile int mark;
private static final AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater(
Once.class, "mark");
private Once() {
}
public static Once create() {
return new Once();
}
public void run(Runnable runnable) {
Objects.requireNonNull(runnable);
if (updater.compareAndSet(this, 0, 1)) {
runnable.run();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy