← Back to Advanced Java Course | Chapter 11: Advanced & Security | Lesson 8 of 19

Java की Atomic Classes

Atomic classes कई threads को किसी number या value को एक-दूसरे पर पैर रखे बिना सुरक्षित रूप से बदलने देती हैं, जैसे एक turnstile जो एक समय में एक व्यक्ति को गिनता है। ये बिना locks के काम करती हैं।
Syntax
java
AtomicInteger counter = new AtomicInteger(initialValue);
counter.incrementAndGet();
counter.compareAndSet(expected, newValue);

Why Atomic Classes?

Atomic classes, जो java.util.concurrent.atomic में define हैं, किसी single variable पर lock-free, thread-safe operations प्रदान करती हैं। वे values को सुरक्षित रूप से update करने के लिए CPU-level Compare-And-Swap (CAS) instructions पर निर्भर करती हैं, साधारण updates के लिए एक traditional lock acquire और release करने का overhead टालते हुए।

उदाहरण: Why Atomic Classes?

java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
	public static void main(String[] args) {
		AtomicInteger counter = new AtomicInteger(0); // lock-free, CAS-based updates
		counter.incrementAndGet();
		System.out.println(counter.get());
	}
}

AtomicInteger Basics

AtomicInteger built-in रूप से thread-safe increment और decrement operations प्रदान करता है -- incrementAndGet() जैसा method ++i जैसा ही काम करता है, लेकिन इसे atomically करता है, इसलिए एक ही counter को increment करने वाले concurrent threads कभी race condition में update नहीं खोते।

उदाहरण: AtomicInteger Basics

java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
	public static void main(String[] args) throws InterruptedException {
		AtomicInteger counter = new AtomicInteger(0);
		Runnable task = () -> { for (int i = 0; i < 1000; i++) counter.incrementAndGet(); };
		Thread t1 = new Thread(task), t2 = new Thread(task);
		t1.start(); t2.start();
		t1.join(); t2.join();
		System.out.println(counter.get()); // reliably 2000
	}
}

AtomicBoolean Toggles

compareAndSet(expected, update) AtomicBoolean के पीछे का core operation है: यह सिर्फ तभी नई value लिखता है जब variable की current value अब भी आपकी उम्मीद से मेल खाती हो, जो वह तरीका है जिससे CAS-based classes कभी block किए बिना conflicting concurrent updates को detect और reject करती हैं।

उदाहरण: AtomicBoolean Toggles

java
import java.util.concurrent.atomic.AtomicBoolean;
public class Main {
	public static void main(String[] args) {
		AtomicBoolean flag = new AtomicBoolean(false);
		boolean changed = flag.compareAndSet(false, true); // only writes if current value matches expected
		System.out.println(changed + " " + flag.get());
	}
}

AtomicReference for Objects

AtomicReference आपको threads के बीच किसी object reference को atomically और सुरक्षित रूप से update करने देता है, जो shared configuration objects, immutable state snapshots, या किसी भी mutable-reference field को manage करने के लिए उपयोगी है जिसे अन्यथा आपको एक lock से सुरक्षित करना होता।

उदाहरण: AtomicReference for Objects

java
import java.util.concurrent.atomic.AtomicReference;
public class Main {
	public static void main(String[] args) {
		AtomicReference<String> config = new AtomicReference<>("v1");
		config.set("v2"); // atomic, safe across threads
		System.out.println(config.get());
	}
}

Performance of Atomic Operations

Atomic operations कभी किसी thread को उस तरह block नहीं करते जैसे एक traditional lock कर सकता है, इसलिए low-to-moderate contention के तहत वे synchronized locking से तेज़ चलते हैं और कम CPU resources उपयोग करते हैं। बहुत ज़्यादा contention के तहत, हालांकि, बार-बार CAS retries अब भी performance घटा सकते हैं, इसलिए ये locks का universal विकल्प नहीं हैं।

उदाहरण: Performance of Atomic Operations

java
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
	public static void main(String[] args) {
		AtomicInteger counter = new AtomicInteger(0);
		long start = System.nanoTime();
		for (int i = 0; i < 100000; i++) counter.incrementAndGet(); // no blocking under low contention
		System.out.println("Took " + (System.nanoTime() - start) + "ns");
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. counter.set(counter.get() + 1) लिखना, जो दो अलग steps हैं जिन्हें कोई दूसरा thread बीच में रोक सकता है; incrementAndGet() का उपयोग करें।
  2. यह मान लेना कि दो atomic variables को एक के बाद एक update करना जोड़ी के रूप में atomic है, जबकि कोई दूसरा thread बीच की state देख सकता है।
  3. यह उम्मीद करना कि AtomicReference.compareAndSet equals उपयोग करेगा, जबकि यह == से references compare करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.