Is is possible to make a method execute only once?

Your can use AtomicBoolean to make sure the task is only called the first time:

import java.util.concurrent.atomic.AtomicBoolean;

public class Once {
    private final AtomicBoolean done = new AtomicBoolean();
    
    public void run(Runnable task) {
        if (done.get()) return;
        if (done.compareAndSet(false, true)) {
            task.run();
        }
    }
}

Usage:

Once once = new Once();
once.run(new Runnable() {
    @Override
    public void run() {
        foo();
    }
});

// or java 8
once.run(() -> foo());

Sure!..

if(!alreadyExecuted) {
    doTrick();
    alreadyExecuted = true;
}

Tags:

Java