Core Java — Collections, Concurrency & Interview Quick Reference

Source concepts preserved from the supplied material. Additional interview topics are clearly marked as added.

1.13.1 Comparator — Java 8 Enhancements

Source content: Comparator in Java 8 is more powerful. Static methods include:
  • Comparator.comparing()
  • Comparator.thenComparing()
  • Comparator.reversed()
people.sort( Comparator.comparing(Person::getAge) .thenComparing(Person::getName) ); people.forEach(person -> System.out.println(person.getName()) );
List<Integer> sortedArrayList = al.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); int k = 2; System.out.println(sortedArrayList.get(k - 1));
Interview answer: Comparator is used when we want custom sorting. Java 8 makes Comparator composition easy using comparing(), thenComparing(), reversed(), nullsFirst(), and nullsLast().

2. How HashMap Works Internally / Is Implemented

Source content: When a key-value pair is inserted, the key's hashCode() is calculated and used to determine the bucket. equals() is then used to identify an existing key. Collisions are handled using a linked structure or tree structure, and the map resizes when its threshold is exceeded.
StepDescription
1️⃣When you put a key-value pair, the key's hashCode() is calculated.
2️⃣That hashCode is used to compute the index (bucket) using index = hash % capacity as described in the source.
3️⃣If the bucket is empty, the new node is stored directly.
4️⃣If the bucket already has a node, equals() is used to check for duplicates.
5️⃣If equals() returns true, the value is updated; otherwise, a new node is added to the chain (linked list or tree).
6️⃣When a bucket's chain becomes too long (threshold = 8 in the supplied material), it is converted into a TreeNode (Red-Black Tree) for faster access.
7️⃣get(key) computes the hashCode() and index, then finds the node by checking keys with equals().
8️⃣If the key is found, the value is returned; otherwise null is returned.
9️⃣HashMap resizes (doubles capacity) when size exceeds threshold = capacity × loadFactor. Default load factor = 0.75.
Important interview concept — hashCode() and equals(): If two keys are equal according to equals(), they must return the same hashCode(). If this contract is broken, HashMap lookups can fail unexpectedly.
Map<String, Integer> map = new HashMap<>(); map.put("A", 100); map.put("B", 200); System.out.println(map.get("A"));

3. How ConcurrentHashMap Is Implemented

ConcurrentHashMap is a thread-safe and highly concurrent implementation of a hash map. It allows multiple threads to read and write without locking the entire map.

StepDescription
1️⃣ConcurrentHashMap uses segments internally in Java 7, but buckets with Node arrays + CAS locking in Java 8+.
2️⃣During put(), the key's hashCode() is computed to determine the bucket index.
3️⃣If the bucket is empty, a new node is inserted using CAS (Compare-And-Swap).
4️⃣If the bucket is not empty, threads use fine-grained locking only on that particular bucket/node.
5️⃣If multiple threads try to write to the same bucket, only one thread locks that bucket — not the entire map.
6️⃣Hash collisions use a linked list and can be converted to tree nodes when the chain grows beyond the threshold described in the source.
7️⃣For reads (get()), volatile reads are used, so reads are mostly lock-free.
8️⃣Resizing is thread-safe and uses transfer bins where threads help in rehashing.
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("A", 100); map.computeIfAbsent("B", key -> 200);
Interview answer: The key idea is that ConcurrentHashMap provides thread-safe concurrent access without one global lock around the complete map. Java 8+ uses a Node-array/bucket design with CAS and synchronized locking at the bin level when required.

4. HashMap vs ConcurrentHashMap

AspectHashMapConcurrentHashMap
Thread safetyNot thread-safeThread-safe
Concurrent accessRequires external synchronization when shared between threadsDesigned for concurrent access
Null keys/valuesAllows null key/value according to HashMap behaviorDoes not allow null keys or null values
LockingNo built-in concurrency controlFine-grained concurrency mechanisms
Use caseNormal single-threaded or externally synchronized mapShared map accessed by multiple threads

5. Thread Safety

A thread-safe class or method ensures that shared data is accessed and modified in a controlled and predictable manner. If two or more threads use it simultaneously, it should function correctly without requiring additional synchronization from the caller.

TechniqueThread SafetyUse Case
synchronized✅ YesSimple critical section control
java.util.concurrent✅ YesCollections and concurrency utilities
Atomic variables✅ YesLock-free counters, flags
Immutable objects✅ YesData that never changes
Thread-local storage✅ YesPer-thread variable isolation
Locks (ReentrantLock)✅ YesFine-grained locking, tryLock, fairness, etc.

6. ReentrantLock Implements Lock

  • It is an implementation class of the Lock interface.
  • Reentrant means a thread that already owns the lock can acquire the same lock again without deadlocking itself.
Lock lock = new ReentrantLock(); lock.lock(); try { // critical section } finally { lock.unlock(); }
Important interview point: Always release an explicitly acquired lock in a finally block. ReentrantLock also provides features such as tryLock(), timed locking, interruptible locking, and optional fairness.

7. Thread-safe LRU Cache

A common approach is to use LinkedHashMap with access-order enabled.

  • LinkedHashMap maintains insertion/access order.
  • Override removeEldestEntry() to implement LRU eviction.
  • Add synchronization or use appropriate concurrent locking for thread safety.
class LRUCache<K,V> extends LinkedHashMap<K,V> { private final int capacity; LRUCache(int capacity) { super(capacity, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return size() > capacity; } }
Interview answer: LinkedHashMap gives us access-order tracking, while removeEldestEntry gives eviction. For a thread-safe implementation, synchronize compound operations or protect the cache with an appropriate lock.

8. Parallel Streams

Parallel streams make use of the Fork/Join framework and its common pool of worker threads.

List<Integer> result = numbers.parallelStream() .filter(n -> n % 2 == 0) .collect(Collectors.toList());
Interview caution: Parallel streams are not automatically faster. They are more appropriate for sufficiently large, CPU-bound, independent operations. Avoid shared mutable state and blocking operations inside parallel stream pipelines.

9. CompletableFuture

CompletableFuture is part of java.util.concurrent. It represents a future result of an asynchronous computation and supports asynchronous, non-blocking composition and chaining.

StepWhat Happens
1️⃣Call an async method such as supplyAsync() or runAsync() to start work in the background.
2️⃣Java executes the task using the ForkJoinPool/common pool or a supplied custom executor.
3️⃣When the task completes, the CompletableFuture is completed with a result or exception.
4️⃣Attach callbacks such as thenApply(), thenAccept(), and thenRun().
5️⃣Combine futures using thenCombine(), allOf(), anyOf(), etc.
6️⃣Block with get() or join() only when necessary; handle exceptions with methods such as exceptionally().
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello"); future.thenApply(result -> result + " World") .thenAccept(System.out::println);
Very important interview distinction:
  • thenApply() — transform a result.
  • thenAccept() — consume a result, returns CompletableFuture<Void>.
  • thenRun() — run an action without using the previous result.
  • thenCompose() — chain dependent asynchronous operations.
  • thenCombine() — combine two independent futures.
  • exceptionally() — recover/handle an exceptional completion.

10. Memory Leaks in Java

  • Memory leaks happen when objects are no longer useful but are still strongly referenced.
  • Tools: VisualVM, Eclipse MAT, JProfiler.
  • Common causes: static collections, listeners not removed, and inner classes holding outer-class references.
  • Fix: remove unnecessary references and use WeakReference when appropriate.
Interview approach to detect a leak: Observe heap growth → capture heap dumps → inspect retained objects/references → identify the GC root keeping objects alive → remove or control that reference → retest.

11. Best Ways to Use Concurrency in Java

  1. Use modern Java concurrency APIs where appropriate instead of manually managing raw Thread objects.
  2. Prefer ForkJoinPool for suitable parallel processing.
  3. Use CompletableFuture for asynchronous programming.
  4. Avoid race conditions with atomic variables or locks.
  5. Avoid deadlocks by consistent lock ordering and minimizing lock scope.
  6. Use ThreadLocal for thread-specific data where appropriate.
  7. Use ScheduledExecutorService for periodic tasks.
  8. Use non-blocking I/O (NIO) for high-performance applications when appropriate.
  9. Prefer Virtual Threads (Java 21) for suitable high-concurrency, I/O-bound workloads.
  10. Monitor and tune thread performance.

12. Additional Important Interview Concepts

These topics are added because they are commonly asked alongside the supplied material.
12.1 synchronized vs volatile vs AtomicInteger
ConceptMain purpose
synchronizedMutual exclusion + visibility for critical sections.
volatileVisibility of a variable across threads; does not make compound operations such as count++ atomic.
AtomicIntegerAtomic operations such as incrementAndGet() without explicit locking.
AtomicInteger counter = new AtomicInteger(0); counter.incrementAndGet();
12.2 Race Condition
A race condition occurs when multiple threads access shared mutable state and the result depends on the timing/interleaving of their execution. Prevent it using synchronization, locks, atomic classes, immutability, or suitable concurrent collections.
12.3 Deadlock, Starvation and Livelock
  • Deadlock: threads wait indefinitely for locks held by each other.
  • Starvation: a thread repeatedly fails to obtain the resources/CPU time it needs.
  • Livelock: threads remain active and respond to each other but make no useful progress.
12.4 ExecutorService — Important Interview Question

ExecutorService manages a pool of worker threads and separates task submission from thread creation/management.

ExecutorService executor = Executors.newFixedThreadPool(5); Future<Integer> future = executor.submit(() -> 10 + 20); System.out.println(future.get()); executor.shutdown();

Remember: shut down executors when they are no longer required.

12.5 Callable vs Runnable
RunnableCallable
run()call()
Does not return a resultReturns a result
Cannot directly throw checked exceptionsCan throw checked exceptions
12.6 Fail-fast vs Fail-safe Iteration

Fail-fast: many standard collection iterators detect structural modification and may throw ConcurrentModificationException.

Concurrent collection iteration: collections such as ConcurrentHashMap provide weakly consistent iteration designed for concurrent use rather than the fail-fast behavior of many ordinary collections.

12.7 HashSet Internals

HashSet is backed by a HashMap. The set element is used as the map key, while an internal dummy value is associated with it. Therefore hashCode() and equals() are critical for correct duplicate detection.

12.8 ArrayList vs LinkedList
AspectArrayListLinkedList
Internal structureResizable arrayDoubly linked list
Random accessFast, O(1) by indexO(n)
Typical useFrequent reads/index accessSpecialized cases involving linked-list operations
12.9 HashMap Key Design

Prefer immutable objects as HashMap keys. If fields used by hashCode()/equals() change after insertion, the entry can become difficult to retrieve because the key may map to a different bucket logically.

12.10 Virtual Threads — Java 21

Virtual threads are lightweight threads designed to make high-concurrency applications easier to write, especially for workloads that spend significant time waiting on I/O.

Thread.startVirtualThread(() -> { System.out.println("Running in a virtual thread"); });
12.11 Thread Pool vs Virtual Threads

Traditional thread pools limit the number of platform threads. Virtual threads are much cheaper to create, so applications can often use many of them for blocking I/O workloads. They do not make CPU-bound work magically faster.

12.12 CompletableFuture: thenCompose vs thenCombine
MethodUse
thenCompose()Dependent async operation; flatten CompletableFuture<CompletableFuture<T>> style chains.
thenCombine()Combine results of two independent asynchronous operations.
12.13 Immutability — Quick Design
  • Make the class final.
  • Make fields private and final.
  • Initialize all fields through the constructor.
  • Do not provide setters.
  • Use defensive copies for mutable input/output objects.
public final class Employee { private final String name; public Employee(String name) { this.name = name; } public String getName() { return name; } }
12.14 Comparable vs Comparator — One-line Answer

Comparable defines the class's natural ordering through compareTo(). Comparator defines external/custom ordering through compare().

12.15 Atomicity, Visibility and Ordering
  • Atomicity: an operation happens as one indivisible unit.
  • Visibility: one thread can see another thread's updates.
  • Ordering: the JVM/compiler/CPU may reorder operations unless concurrency rules establish the required ordering.

13. Rapid-fire Interview Questions

Why is HashMap not thread-safe?
Because it does not provide synchronization/concurrency control for simultaneous modifications by multiple threads.
Why does ConcurrentHashMap not allow null?
Its concurrent retrieval semantics need to distinguish absence from a stored null value, so null keys and values are not permitted.
What is CAS?
Compare-And-Swap is an atomic CPU-level operation used by concurrency algorithms to update a value only if it still has the expected value.
Why use ReentrantLock instead of synchronized?
When you need capabilities such as tryLock(), timed locking, interruptible locking, or optional fairness.
Why use CompletableFuture?
To compose asynchronous operations, chain dependent tasks, combine independent tasks, and handle completion/errors without manually coordinating threads.
When should you avoid parallel streams?
When the workload is small, operations are heavily blocking, ordering is important, or the pipeline uses shared mutable state.
What causes a Java memory leak?
Objects remain strongly reachable even though the application no longer needs them. Common examples include static collections and listeners that are never removed.
What is the difference between get() and join() on CompletableFuture?
Both can wait for completion. get() works with checked exceptions, while join() throws CompletionException for exceptional completion.
What is the difference between synchronized and Lock?
synchronized provides built-in monitor locking with automatic release. Lock implementations such as ReentrantLock provide explicit lock management and additional features.
What is a good answer for "How do you prevent deadlocks?"
Use consistent lock ordering, minimize lock scope, avoid nested locks where possible, use tryLock/timeouts where appropriate, and prefer higher-level concurrency utilities.