All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.concurrent.Once Maven / Gradle / Ivy

There is a newer version: 12.0.2
Show newest version
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