java.util.concurrent.atomic.AtomicInteger is a class in the java.util.concurrent.atomic package. It represents an integer value that can be updated atomically.
Example 1:
AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); System.out.println(count.get());
In this example, an AtomicInteger is created with an initial value of 0. The incrementAndGet() method is called to atomically increment the value by 1 and return the new value. Finally, the get() method is called to retrieve the current value, which is printed to the console.
Example 2:
AtomicInteger balance = new AtomicInteger(100); int amount = 50; if (balance.compareAndSet(100, balance.get() - amount)) { System.out.println("Withdrawal successful. New balance: " + balance.get()); } else { System.out.println("Withdrawal failed. Insufficient balance."); }
In this example, an AtomicInteger is created with an initial value of 100 representing a bank balance. The amount to withdraw is 50. The compareAndSet() method is called to atomically check if the current value is 100 and update it to the new value of balance - amount if it is. If the update is successful, the withdrawal is considered successful, and the new balance is printed to the console. If the update fails, it means that the balance was changed between the check and update, and the withdrawal failed due to insufficient balance.
AtomicInteger is a class in the java.util.concurrent.atomic package.
Java AtomicInteger - 30 examples found. These are the top rated real world Java examples of java.util.concurrent.atomic.AtomicInteger extracted from open source projects. You can rate examples to help us improve the quality of examples.