import java.util.concurrent.atomic.AtomicInteger; class Counter { private AtomicInteger count = new AtomicInteger(0); public int incrementAndGet() { return count.incrementAndGet(); } public int getAndDecrement() { return count.getAndDecrement(); } } Counter counter = new Counter(); counter.incrementAndGet(); // 1 counter.getAndDecrement(); // 1, decrements and returns previous count (i.e., 1)
import java.util.concurrent.atomic.AtomicInteger; class CountdownTimer { private AtomicInteger timeLeft; public CountdownTimer(int time) { timeLeft = new AtomicInteger(time); } public int getTimeLeft() { return timeLeft.get(); } public boolean countdown() { return timeLeft.getAndDecrement() > 0; } } CountdownTimer timer = new CountdownTimer(5); timer.countdown(); // true, decrements and returns 4 timer.countdown(); // true, decrements and returns 3 timer.countdown(); // true, decrements and returns 2 timer.countdown(); // true, decrements and returns 1 timer.countdown(); // false, decrements and returns 0The examples above demonstrate how Java's AtomicInteger class and its getAndDecrement() method can be used to perform safe atomic operations on shared mutable variables. The getAndDecrement() method is part of the java.util.concurrent.atomic package in Java.