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:
-
Thread synchronization:
- Use the
synchronizedkeyword or locks (Lock) to prevent concurrent execution of the operation.
- Use the
-
State flag:
- Introduce a boolean flag that is set during the first execution of the operation, and check it before executing.
-
Using
AtomicBooleanorvolatilevariables:- For thread-safe control of the operation's state.
-
Singleton pattern or lazy initialization:
- For example, using
java.util.concurrent.atomic.AtomicBoolean:
- For example, using
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.