Java की Concurrent Collections
In this page:
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?
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"));
}
}
Login to try C/C++/Java/PHP code in the editor
ConcurrentHashMap
ConcurrentHashMap कई threads से सुरक्षित concurrent reads और writes की अनुमति देता है। यह पूरे table के बजाय map के सिर्फ specific segments (या modern implementations में, individual bins) को lock करता है, इसलिए अलग-अलग keys पर काम करने वाले असंबंधित threads शायद ही कभी एक-दूसरे को block करते हैं।
उदाहरण: ConcurrentHashMap
// 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());
}
}
Login to try C/C++/Java/PHP code in the editor
CopyOnWriteArrayList
CopyOnWriteArrayList एक thread-safe list है जो हर mutation (add, set, remove) पर अपने underlying array की एक पूरी तरह नई copy बनाती है। यह writes को अपेक्षाकृत महंगा बनाता है, लेकिन reads को बिल्कुल कोई locking नहीं चाहिए, जो इसे उन lists के लिए आदर्श बनाता है जो लगातार पढ़ी जाती हैं लेकिन कभी-कभार ही modify होती हैं।
उदाहरण: CopyOnWriteArrayList
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
}
}
Login to try C/C++/Java/PHP code in the editor
BlockingQueue
BlockingQueue producer-consumer patterns के लिए डिज़ाइन की गई एक thread-safe queue है: यह queue भरी होने पर producer thread को अपने आप block करती है और queue खाली होने पर consumer thread को block करती है, आपके manual wait/notify logic लिखे बिना दोनों पक्षों को coordinate करते हुए।
उदाहरण: BlockingQueue
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();
}
}
Login to try C/C++/Java/PHP code in the editor
ConcurrentSkipListMap
ConcurrentSkipListMap एक concurrent, sorted map implementation है जो अपनी keys को हमेशा sorted order में बनाए रखता है, उन स्थितियों के लिए TreeMap का एक scalable, thread-safe विकल्प प्रदान करते हुए जहां कई threads को shared data तक sorted access चाहिए।
उदाहरण: ConcurrentSkipListMap
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
}
}
Login to try C/C++/Java/PHP code in the editor
- किसी
ConcurrentHashMapपरif (!map.containsKey(k)) map.put(k, v)लिखना, जो atomic नहीं है;putIfAbsentयाcomputeIfAbsentका उपयोग करें। - किसी
ConcurrentHashMapमेंnullkey या value डालना, जोNullPointerExceptionफेंकता है। - अक्सर लिखी जाने वाली list के लिए
CopyOnWriteArrayListका उपयोग करना, क्योंकि हर write पूरे array को copy करता है।
Chapter Quiz — Complete all 19 topics to unlock
0/19 topics done
Complete these topics first:
- Java Reflection API
- Java Annotations Advanced
- Java Garbage Collection
- Java Memory Management
- Java Performance Optimization
- Java Advanced Interview Questions
- Java CompletableFuture
- Java Atomic Classes
- Java Locks & Semaphores
- Java Concurrent Collections
- Java Cryptography Basics
- Java Hashing (MD5, SHA)
- Java SSL & HTTPS
- Java Logging (Log4j/SLF4J)
- Java Serialization Advanced
- Java Interview Questions Advanced
- Java Connection Pooling
- Java Test Driven Development
- Java Integration Testing