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

Java की Concurrent Collections

Concurrent collections ऐसी lists और maps हैं जो एक साथ कई threads द्वारा सुरक्षित रूप से उपयोग होने के लिए बनी हैं, जैसे अच्छे manners वाला एक shared whiteboard। Regular वाले share होने पर गड़बड़ा सकते हैं।
Syntax
java
ConcurrentHashMap<KeyType, ValueType> map = new ConcurrentHashMap<>();
map.put(key, value);
CopyOnWriteArrayList<Type> list = new CopyOnWriteArrayList<>();

Why Concurrent Collections?

java.util.concurrent में defined Concurrent collections, किसी regular collection को Collections.synchronizedList() या similar से wrap करने के high-performance, thread-safe विकल्प प्रदान करती हैं। वे हर access पर पूरी structure को lock करने के बजाय underlying data को segment करके lock contention घटाती हैं।

उदाहरण: Why Concurrent Collections?

java
import java.util.concurrent.ConcurrentHashMap;
public class Main {
	public static void main(String[] args) {
		ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); // segmented, not one big lock
		map.put("a", 1);
		System.out.println(map.get("a"));
	}
}

ConcurrentHashMap

ConcurrentHashMap कई threads से सुरक्षित concurrent reads और writes की अनुमति देता है। यह पूरे table के बजाय map के सिर्फ specific segments (या modern implementations में, individual bins) को lock करता है, इसलिए अलग-अलग keys पर काम करने वाले असंबंधित threads शायद ही कभी एक-दूसरे को block करते हैं।

उदाहरण: ConcurrentHashMap

java
// Import java.util.concurrent.ConcurrentHashMap so it can be used by its short name
import java.util.concurrent.ConcurrentHashMap;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws InterruptedException {
		// Create a new ConcurrentHashMap object and store it in map
		ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
		Runnable task = () -> { for (int i = 0; i < 100; i++) map.put(i, i); };
		// Create a new Thread object and store it in t1
		Thread t1 = new Thread(task), t2 = new Thread(task);
		// Start the thread; it runs in parallel with this code
		t1.start(); t2.start();
		// Wait for the thread to finish
		t1.join(); t2.join();
		// Print a line to the console
		System.out.println(map.size());
	}
}

CopyOnWriteArrayList

CopyOnWriteArrayList एक thread-safe list है जो हर mutation (add, set, remove) पर अपने underlying array की एक पूरी तरह नई copy बनाती है। यह writes को अपेक्षाकृत महंगा बनाता है, लेकिन reads को बिल्कुल कोई locking नहीं चाहिए, जो इसे उन lists के लिए आदर्श बनाता है जो लगातार पढ़ी जाती हैं लेकिन कभी-कभार ही modify होती हैं।

उदाहरण: CopyOnWriteArrayList

java
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
	public static void main(String[] args) {
		CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); // copies the array on every write
		list.add("a"); // relatively expensive
		for (String item : list) System.out.println(item); // reads need no locking at all
	}
}

BlockingQueue

BlockingQueue producer-consumer patterns के लिए डिज़ाइन की गई एक thread-safe queue है: यह queue भरी होने पर producer thread को अपने आप block करती है और queue खाली होने पर consumer thread को block करती है, आपके manual wait/notify logic लिखे बिना दोनों पक्षों को coordinate करते हुए।

उदाहरण: BlockingQueue

java
import java.util.concurrent.*;
public class Main {
	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);
		queue.put(1); // fills the queue
		Thread consumer = new Thread(() -> {
			try { System.out.println("Consumed: " + queue.take()); } catch (InterruptedException e) {}
		});
		consumer.start();
		consumer.join();
	}
}

ConcurrentSkipListMap

ConcurrentSkipListMap एक concurrent, sorted map implementation है जो अपनी keys को हमेशा sorted order में बनाए रखता है, उन स्थितियों के लिए TreeMap का एक scalable, thread-safe विकल्प प्रदान करते हुए जहां कई threads को shared data तक sorted access चाहिए।

उदाहरण: ConcurrentSkipListMap

java
import java.util.concurrent.ConcurrentSkipListMap;
public class Main {
	public static void main(String[] args) {
		ConcurrentSkipListMap<Integer, String> map = new ConcurrentSkipListMap<>();
		map.put(3, "c"); map.put(1, "a"); map.put(2, "b");
		System.out.println(map); // always sorted, thread-safe
	}
}
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. किसी ConcurrentHashMap पर if (!map.containsKey(k)) map.put(k, v) लिखना, जो atomic नहीं है; putIfAbsent या computeIfAbsent का उपयोग करें।
  2. किसी ConcurrentHashMap में null key या value डालना, जो NullPointerException फेंकता है।
  3. अक्सर लिखी जाने वाली list के लिए CopyOnWriteArrayList का उपयोग करना, क्योंकि हर write पूरे array को copy करता है।

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.