1.13.1 Comparator — Java 8 Enhancements
- Comparator.comparing()
- Comparator.thenComparing()
- Comparator.reversed()
2. How HashMap Works Internally / Is Implemented
| Step | Description |
|---|---|
| 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. |
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.
| Step | Description |
|---|---|
| 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. |
4. HashMap vs ConcurrentHashMap
| Aspect | HashMap | ConcurrentHashMap |
|---|---|---|
| Thread safety | Not thread-safe | Thread-safe |
| Concurrent access | Requires external synchronization when shared between threads | Designed for concurrent access |
| Null keys/values | Allows null key/value according to HashMap behavior | Does not allow null keys or null values |
| Locking | No built-in concurrency control | Fine-grained concurrency mechanisms |
| Use case | Normal single-threaded or externally synchronized map | Shared 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.
| Technique | Thread Safety | Use Case |
|---|---|---|
| synchronized | ✅ Yes | Simple critical section control |
| java.util.concurrent | ✅ Yes | Collections and concurrency utilities |
| Atomic variables | ✅ Yes | Lock-free counters, flags |
| Immutable objects | ✅ Yes | Data that never changes |
| Thread-local storage | ✅ Yes | Per-thread variable isolation |
| Locks (ReentrantLock) | ✅ Yes | Fine-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.
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.
8. Parallel Streams
Parallel streams make use of the Fork/Join framework and its common pool of worker threads.
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.
| Step | What 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(). |
- 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.
11. Best Ways to Use Concurrency in Java
- Use modern Java concurrency APIs where appropriate instead of manually managing raw Thread objects.
- Prefer ForkJoinPool for suitable parallel processing.
- Use CompletableFuture for asynchronous programming.
- Avoid race conditions with atomic variables or locks.
- Avoid deadlocks by consistent lock ordering and minimizing lock scope.
- Use ThreadLocal for thread-specific data where appropriate.
- Use ScheduledExecutorService for periodic tasks.
- Use non-blocking I/O (NIO) for high-performance applications when appropriate.
- Prefer Virtual Threads (Java 21) for suitable high-concurrency, I/O-bound workloads.
- Monitor and tune thread performance.
12. Additional Important Interview Concepts
12.1 synchronized vs volatile vs AtomicInteger
| Concept | Main purpose |
|---|---|
| synchronized | Mutual exclusion + visibility for critical sections. |
| volatile | Visibility of a variable across threads; does not make compound operations such as count++ atomic. |
| AtomicInteger | Atomic operations such as incrementAndGet() without explicit locking. |
12.2 Race Condition
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.
Remember: shut down executors when they are no longer required.
12.5 Callable vs Runnable
| Runnable | Callable |
|---|---|
| run() | call() |
| Does not return a result | Returns a result |
| Cannot directly throw checked exceptions | Can 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
| Aspect | ArrayList | LinkedList |
|---|---|---|
| Internal structure | Resizable array | Doubly linked list |
| Random access | Fast, O(1) by index | O(n) |
| Typical use | Frequent reads/index access | Specialized 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.
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
| Method | Use |
|---|---|
| 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.
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.