Java Collections and Concurrency Concepts
PriorityQueue in Java
PriorityQueue in Java is a Queue implementation that orders elements by priority (natural order or
comparator).
Key Points:
- Implements Queue interface.
- Orders elements using natural ordering or a custom Comparator.
- Does not allow null elements.
- Allows duplicate elements.
- Requires homogeneous elements when using Comparable.
- If a Comparator is provided, all elements must be comparable under that comparator.
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](10);
[Link](5);
[Link](20);
[Link](5); // duplicate allowed
while (![Link]()) {
[Link]([Link]());
}
ConcurrentHashMap in Java
ConcurrentHashMap is a thread-safe hash table implementation that uses fine-grained locking.
Key Points:
- Thread-safe and allows concurrent reads and updates.
- Uses bucket-level locking (Java 8+) or segments (Java 7).
- Default capacity is 16 buckets with load factor 0.75.
- Does not allow null keys or null values.
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
// [Link](null, "Cherry"); // NullPointerException
// [Link](3, null); // NullPointerException
HashMap vs ConcurrentHashMap
Aspect HashMap ConcurrentHashMap
Thread Safety
Not thread-safeThread-safe
Synchronization
None Fine-grained locking
Null Keys Allowed Not allowed
Null Values Allowed Not allowed
Iteration Fail-fast Weakly consistent
PerformanceFaster (single-threaded)
Better (multi-threaded)
CopyOnWriteArrayList
CopyOnWriteArrayList is a thread-safe variant of ArrayList that allows nulls, duplicates, and
heterogeneous elements.
It implements Serializable, Cloneable, and RandomAccess. Reads are lock-free and
snapshot-based, while writes (add, remove, update)
create a new copy of the array under a lock. Removal affects the new copy, ensuring readers
always see a consistent snapshot.
CopyOnWriteArraySet
CopyOnWriteArraySet is a thread-safe variant of Set that does not allow duplicates but allows null
elements.
It implements Serializable and Cloneable. Internally, it is backed by a CopyOnWriteArrayList, which
means all read operations
are lock-free and snapshot-based, while write operations (add, remove, update) create a new copy
of the underlying array under a lock.
Since it is a Set, duplicate insertions are ignored, but null insertion is permitted once. Removal
affects the new copy,
ensuring readers always see a consistent snapshot without blocking.