top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java : Handling Concurrency through Atomic Integers

Introduction: In Java, multiple threads can access and modify the same variable concurrently, leading to race conditions and incorrect results. To avoid this problem, the AtomicInteger class is used to provide thread-safe operations on integer values.

Explanation: AtomicInteger provides atomic operations such as increment, decrement, and compare-and-set, which can be safely used by multiple threads concurrently. The operations are implemented in a way that ensures that they are executed as a single, indivisible unit, thereby avoiding race conditions.

Here is an example code that demonstrates the use of AtomicInteger to increment a shared counter safely:


import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {

    public static void main(String[] args) {
        AtomicInteger counter = new AtomicInteger(0); // initialize the counter with a value of 0Runnable task = () -> {
            for (int i = 0; i < 10000; i++) {
                counter.incrementAndGet(); // atomically increment the counter
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        Thread thread3 = new Thread(task);

        thread1.start();
        thread2.start();
        thread3.start();

        try {
            thread1.join();
            thread2.join();
            thread3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Counter value: " + counter.get());
    }
}

In this example, we create an AtomicInteger with an initial value of 0. We then create a Runnable task that atomically increments the counter 10,000 times. We create three threads that execute the task concurrently.

Since the incrementAndGet() method is atomic, we can safely use it to increment the counter concurrently without worrying about race conditions.

After all the threads have completed executing, we print the final value of the counter.

Sample Output:


Counter value: 30000

As expected, the final value of the counter is 30,000, which is the sum of the 10,000 increments performed by each of the three threads. This demonstrates how AtomicInteger can be used to safely perform atomic operations on shared variables in a multithreaded environment.

31 views

Recent Posts

See All

Comments


bottom of page