User Tools

Site Tools


java:threads:atomic-variables

Atomic Variables in Java Threads

Atomic variables in Java, provided by the java.util.concurrent.atomic package, are used for operations that need to be performed atomically to avoid thread interference without using synchronization. They are often used in concurrent programming where multiple threads need to modify a shared variable reliably.

AtomicVariableExample.java
import java.util.concurrent.atomic.AtomicInteger;
 
public class AtomicVariableExample {
    // Atomic integer variable
    private final AtomicInteger count = new AtomicInteger(0);
 
    public void increment() {
        // Atomically increments by one the current value
        count.incrementAndGet();
    }
 
    public void decrement() {
        // Atomically decrements by one the current value
        count.decrementAndGet();
    }
 
    public int getCount() {
        // Returns the current value
        return count.get();
    }
 
    public static void main(String[] args) throws InterruptedException {
        AtomicVariableExample example = new AtomicVariableExample();
 
        // Thread for incrementing the count
        Thread incrementThread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });
 
        // Thread for decrementing the count
        Thread decrementThread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.decrement();
            }
        });
 
        incrementThread.start();
        decrementThread.start();
 
        // Wait for both threads to finish
        incrementThread.join();
        decrementThread.join();
 
        // Print the final count value
        System.out.println("Final count value: " + example.getCount());
    }
}

AtomicInteger: We use AtomicInteger for the count variable to ensure that all operations on this variable are performed atomically.

Increment and Decrement Methods: The increment() and decrement() methods use incrementAndGet() and decrementAndGet() respectively, which are atomic operations provided by AtomicInteger.

Thread-Safe Operations: The atomic operations on count ensure that its value is correctly updated even when accessed from multiple threads, without explicit synchronization.

Testing the Atomic Variable: In the main method, we create two threads. One increments the count 1000 times, and the other decrements it 1000 times. After both threads have completed their execution, we print the final value of count.

Expected Output: If the atomic operations work correctly, the final count value should be 0 as the number of increments and decrements are equal.

This example demonstrates the use of atomic variables to perform thread-safe operations without the overhead of synchronization. Atomic variables are essential in concurrent programming for simple atomic operations like incrementing a counter, updating a flag, etc., ensuring data consistency and thread safety.

java/threads/atomic-variables.txt · Last modified: 2024/01/17 03:00 by odefta