Java

Java Collections & Concurrency

List, Set, Map implementations, time complexity, ConcurrentHashMap, iterators, and thread-safe patterns.

Interview tip Say complexity aloud: "HashMap get/put O(1) average; ArrayList get O(1), insert middle O(n)."

① Collection hierarchy overview

Iterable → Collection → List, Set, Queue
List — ordered, allows duplicates (ArrayList, LinkedList)
Set — no duplicates (HashSet, LinkedHashSet, TreeSet)
Queue / Deque — FIFO, LIFO (ArrayDeque, PriorityQueue, BlockingQueue)
Map — key-value (separate hierarchy): HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap
Prefer interfaces in API signatures: List<T>, Map<K,V> — swap implementations without breaking callers.

② List implementations

ImplementationBackinggetadd/endadd/middleUse when
ArrayListDynamic arrayO(1)O(1)* amortizedO(n)Default list — random access
LinkedListDoubly linked nodesO(n)O(1)O(1)* with iteratorDeque ops, rare — ArrayDeque often better
CopyOnWriteArrayListCopy on writeO(1)O(n) copyO(n)Read-heavy, rare writes (listeners)
*LinkedList rarely wins — cache-unfriendly; ArrayDeque for queue/stack.

③ Set implementations

ImplementationOrderComplexityNotes
HashSetNoneO(1) avg add/containsBacked by HashMap
LinkedHashSetInsertion orderO(1) avgPredictable iteration
TreeSetSorted (natural/Comparator)O(log n)Red-black tree; no null
EnumSetEnum declaration orderO(1)Bit vector — very compact

④ Map implementations

ImplementationOrderNull key/valueThread-safeUse
HashMapNone1 null key, null values OKNoDefault map
LinkedHashMapInsertion or access orderSame as HashMapNoLRU cache with removeEldestEntry
TreeMapSorted keysNo null keyNoRange queries, navigableMap
ConcurrentHashMapNoneNo nullsYesConcurrent reads/writes
HashtableNoneNo nullsYes (legacy)Avoid — use ConcurrentHashMap
HashMap internals (Java 8+): array of buckets → linked list or tree (if bucket > 8 nodes). Load factor 0.75; resize 2× when threshold exceeded.

⑤ ConcurrentHashMap deep dive

Java 8+ ConcurrentHashMap: bucket-level locking (synchronized first node) or CAS for empty buckets — finer granularity than pre-8 segment locks. Reads generally lock-free.

No null keys/values — ambiguity in concurrent context.

Atomic operations: putIfAbsent, compute, merge — atomic read-modify-write.
vs Collections.synchronizedMapConcurrentHashMap
Lock scopeEntire mapPer-bucket / CAS
Read concurrencyOne at a timeMultiple concurrent reads
IterationMust external syncWeakly consistent iterator
NullsAllowed (HashMap)Not allowed

⑥ Iterators — fail-fast vs weakly consistent

Fail-fast: ArrayList, HashMap iterators throw ConcurrentModificationException if collection structurally modified during iteration (except iterator's own remove). Detected via modCount.

Fix: use iterator.remove(), copy collection, or concurrent collection.
Weakly consistent: ConcurrentHashMap, CopyOnWriteArrayList — iterator reflects state at creation time; may or may not see concurrent updates; never throws CME.

⑦ Concurrency essentials

MechanismPurposePitfall
synchronizedMutual exclusion on object monitorDeadlock if lock order inconsistent
ReentrantLockExplicit lock, tryLock, fairnessMust unlock in finally
volatileVisibility across threadsNot atomic for i++ — use AtomicInteger
Atomic* classesLock-free CAS operationsABA problem rare in Java util
ExecutorServiceThread pool abstractionUnbounded queue → OOM under load
Thread pool pattern
Producer threads
BlockingQueue
ThreadPoolExecutor
Worker tasks

⑧ BlockingQueue types

QueueBehaviorUse
ArrayBlockingQueueBounded array, one lockFixed capacity backpressure
LinkedBlockingQueueOptional bounded linked nodesCommon in Executors — watch unbounded
SynchronousQueueZero capacity — handoffCachedThreadPool direct transfer
PriorityBlockingQueueUnbounded priority heapScheduled tasks by priority
DelayQueueElements available after delayScheduled execution
Design pattern: producers put(), worker pool take() — decouples rate; bounded queue prevents memory blowup.

⑨ Interview Q&A

QuestionAnswer sketch
HashMap vs Hashtable?HashMap not sync, allows null key; Hashtable legacy synchronized — use ConcurrentHashMap
Comparable vs Comparator?Comparable natural order in class; Comparator external, multiple sort orders
How HashSet stores elements?HashMap with dummy PRESENT value — uniqueness via keys
LRU cache in Java?LinkedHashMap(accessOrder=true) + removeEldestEntry override
CopyOnWriteArrayList when?Many readers, few writers — snapshot iteration, expensive writes

⑩ Revision checklist

  • Picked List/Set/Map impl with complexity justification
  • Explained HashMap bucket → list/tree structure
  • Contrasted ConcurrentHashMap vs synchronizedMap
  • Described fail-fast CME cause and fixes
  • Designed worker pool with BlockingQueue type choice
  • Named atomic classes vs volatile for counters
ArrayListHashMapConcurrentHashMapBlockingQueueconcurrency