Senior
What are Atomic classes and what are they used for?
sobes.tech AI
Answer from AI
Atomic classes in Java are classes from the java.util.concurrent.atomic package that provide operations on variables with guaranteed atomicity without using locks.
They are used for safe modification of values in a multithreaded environment, helping to avoid race conditions and ensuring data correctness during concurrent access.
Examples of such classes:
- AtomicInteger
- AtomicLong
- AtomicReference<T>
Example of using AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
Here, incrementAndGet() is an atomic operation that increases the value, ensuring that even when called simultaneously from different threads, the value is not lost.