Junior — Middle
Which interfaces in programming ensure the execution of operations atomically?
sobes.tech AI
Answer from AI
In Java, interfaces from the java.util.concurrent.atomic package are used to ensure atomic execution of operations. The main interfaces are AtomicInteger, AtomicLong, AtomicReference, and other classes that provide atomic operations on variables.
Although Java does not have a separate interface named "Atomic," atomic operations are implemented through these classes, which provide:
- Atomic read and write
- Atomic update operations (e.g., incrementAndGet, compareAndSet)
Example of using AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicExample {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet(); // atomic increment
}
public int getCounter() {
return counter.get();
}
}
Thus, in Java, classes from java.util.concurrent.atomic are used for atomic operations, not interfaces in the traditional sense.