Sobes.tech
Junior — Middle

How can you ensure a one-time operation and prevent it from being executed again?

sobes.tech AI

Answer from AI

To ensure that an operation is performed only once and to prevent its repeated execution, several approaches can be used:

  1. Thread synchronization:

    • Use the synchronized keyword or locks (Lock) to prevent concurrent execution of the operation.
  2. State flag:

    • Introduce a boolean flag that is set during the first execution of the operation, and check it before executing.
  3. Using AtomicBoolean or volatile variables:

    • For thread-safe control of the operation's state.
  4. Singleton pattern or lazy initialization:

    • For example, using java.util.concurrent.atomic.AtomicBoolean:
import java.util.concurrent.atomic.AtomicBoolean;

public class OneTimeOperation {
    private final AtomicBoolean executed = new AtomicBoolean(false);

    public void execute() {
        if (executed.compareAndSet(false, true)) {
            // Code of the operation that should be executed only once
            System.out.println("Operation completed");
        } else {
            System.out.println("Operation has already been executed before");
        }
    }
}

Thus, the operation will only be executed once, even if multiple threads try to start it simultaneously.

How can you ensure a one-time operation and prevent… - sobes.tech