Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are Atomic operations and Atomic classes in Java? When should you use them? Java में Atomic operations और Atomic classes क्या हैं? कब use करते हैं?

Answer

Atomic classes provide thread-safe operations on single variables without synchronization. They use Compare-And-Swap (CAS) operations for lock-free thread safety, offering better performance than synchronized blocks for simple operations.

import java.util.concurrent.atomic.*;

// Problem: Without atomicity
public class NonAtomic {
    private int counter = 0;
    
    public void increment() {
        counter++;  // NOT atomic
    }
}

// Solution: Atomic classes
public class AtomicDemo {
    private AtomicInteger counter = new AtomicInteger(0);
    
    public void increment() {
        counter.incrementAndGet();  // Atomic operation
    }
    
    public int getCounter() {
        return counter.get();
    }
    
    public static void main(String[] args) {
        AtomicDemo demo = new AtomicDemo();
        
        // 10 threads, each increments 10000 times
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    demo.increment();
                }
            }).start();
        }
        
        try {
            Thread.sleep(2000);
            System.out.println('Counter: ' + demo.getCounter());  // 100000
        } catch (InterruptedException e) {}
    }
}

// Common Atomic Classes

// 1. AtomicInteger
AtomicInteger ai = new AtomicInteger(0);
ai.incrementAndGet();     // ++i
ai.decrementAndGet();     // --i
ai.addAndGet(5);          // Add 5
ai.getAndAdd(5);          // Get old, add 5
ai.compareAndSet(0, 1);   // CAS operation

// 2. AtomicLong
AtomicLong al = new AtomicLong(0);
al.incrementAndGet();

// 3. AtomicBoolean
AtomicBoolean flag = new AtomicBoolean(false);
flag.set(true);
flag.get();

// 4. AtomicReference
AtomicReference<String> ref = new AtomicReference<>('initial');
ref.set('new value');

// 5. AtomicIntegerArray
AtomicIntegerArray array = new AtomicIntegerArray(10);
array.incrementAndGet(0);

// Compare-And-Swap (CAS) internally
public class CASDemo {
    public static void main(String[] args) {
        AtomicInteger ai = new AtomicInteger(10);
        
        // CAS: if value == 10, set to 20
        boolean success = ai.compareAndSet(10, 20);
        System.out.println('Success: ' + success);  // true
        System.out.println('Value: ' + ai.get());   // 20
        
        // CAS: if value == 10, set to 30 (fails)
        success = ai.compareAndSet(10, 30);
        System.out.println('Success: ' + success);  // false
    }
}

// Performance: Atomic vs Synchronized
// For 1M increments:
// Synchronized: ~100ms
// Atomic: ~10ms (10x faster)
// Reason: No lock contention, lock-free CAS
Atomic Operations:

Advantage: Synchronization के बिना thread-safe

Common Atomic Classes:
1. AtomicInteger
2. AtomicLong
3. AtomicBoolean
4. AtomicReference
5. AtomicIntegerArray

Usage:
AtomicInteger ai = new AtomicInteger(0);
ai.incrementAndGet();  // ++ai
ai.getAndAdd(5);       // Get old, add 5
ai.compareAndSet(0,1); // CAS operation

How it works:
CAS (Compare-And-Swap) internally
- No locks needed
- Lock-free operations
- Better performance

When to use:
- Simple operations (++, get, set)
- NOT for complex logic
- Multiple variables -> use synchronized

Performance: 10x faster than synchronized

Was this answer clear?