Advanced Java, Distributed Systems & Integration Architecture Master GuideCategory
1: Core Java & JDK Internals (Advanced)
Q: How do Virtual Threads (Project Loom) differ from platform threads in terms of memory?
A: Platform threads have a fixed-size stack (typically ~1MB) allocated directly by the Operating System. Virtual threads are managed entirely by the JVM, and their stack frames are stored as objects on the Java Heap, growing and shrinking dynamically as needed.
Q: Explain the 'Happens-Before' relationship in the Java Memory Model.
A: It’s a formal guarantee that memory writes by one specific statement are guaranteed to be visible to another specific statement in another thread. For example, a write to a volatile field happens-before every subsequent read of that same field.
Q: Why is invokedynamic important for Java 8+?
A: It allows the JVM to delay the binding of a method call until runtime. This was essential for implementing Lambdas efficiently without creating thousands of synthetic anonymous .class files on disk during compilation.
Q: How does the G1 Garbage Collector handle "Humongous Objects"?
A: Objects larger than 50% of a G1 region size are designated as "Humongous." They are allocated in special contiguous sequences of regions directly in the Old Generation and can be reclaimed during the cleanup phase or a Full GC.
Q: What are Scoped Values (JEP 446)?
A: A modern alternative to ThreadLocal, designed specifically for Virtual Threads. They allow sharing immutable data across a large number of threads with lower memory overhead, zero footprint leak risks, and a clear, lexically bounded lifecycle.
Q: Explain the difference between poll() and epoll in the context of Java NIO.
A:
Q: What is "False Sharing" and how does @Contended fix it?
A: False Sharing occurs when two threads running on different CPU cores modify distinct variables that happen to reside on the same 64-byte CPU cache line. Writes by one core invalidate the entire cache line for the other core, causing severe cache-line bouncing. @Contended inserts automatic memory padding around fields to force them onto separate cache lines.
Q: How would you detect a deadlock programmatically in a running JVM?
A: Use ThreadMXBean.findDeadlockedThreads().
Q: What is the difference between Strong, Soft, Weak, and Phantom references?
A:
Q: How does String.intern() work in Java 17+?
A: It checks the global String Constant Pool. If the string exists, it returns the reference; otherwise, it adds the string to the pool. Since Java 7, the pool resides in the main Heap (not PermGen/Metaspace), allowing interned strings to be garbage collected if no longer referenced.
Category 2: Concurrency & Multithreading
Q: Compare synchronized vs ReentrantLock.
A: ReentrantLock offers advanced features like fairness selection, non-blocking lock acquisition (tryLock()), interruptible lock waits, and multiple Condition objects. synchronized is simpler, managed at the language/bytecode level, and automatically optimized by the JVM runtime (e.g., lock coarsen/elision).
Q: What is a CompletableFuture and how does it handle exceptions?
A: It’s a non-blocking, composable Future for asynchronous programming. Exceptions are propagated down the execution pipeline and handled gracefully via .exceptionally() or .handle(), allowing recovery or fallback execution.
Q: How does LongAdder outperform AtomicLong under high contention?
A: AtomicLong uses a single shared CAS (Compare-And-Swap) variable; under high thread contention, most threads spin endlessly failing CAS updates. LongAdder maintains a dynamic array of internal Cell objects to distribute increment operations across threads, summing them up when .sum() is called.
Q: Explain Phaser vs CyclicBarrier vs CountDownLatch.
A:
Q: What is the "Thundering Herd" problem in thread pools?
A: Occurs when a large number of waiting threads are woken up simultaneously to handle a task event, but only one thread can claim the task while the rest go back to sleep, causing excessive CPU context-switching spikes. Proper queue orchestration in ThreadPoolExecutor mitigates this.
Q: How would you implement a Rate Limiter vs Concurrency Limiter using Semaphore?A:
Q: Why should you avoid Executors.newFixedThreadPool(n) for high-throughput apps?
A: Executors.newFixedThreadPool(n) uses an unbounded LinkedBlockingQueue (default capacity = Integer.MAX_VALUE).
Deep Dive & Internal Mechanics:
When you create a fixed thread pool, the JVM instantiates a ThreadPoolExecutor with corePoolSize = n and maximumPoolSize = n:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(
nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>() // Unbounded Queue!
);
}
Production Solution:
Always construct explicit ThreadPoolExecutor instances with bounded queues and an explicit backpressure rejection policy:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
coreThreads, maxThreads, 60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000), // Bounded Queue
new ThreadPoolExecutor.CallerRunsPolicy() // Backpressure strategy
);
Q: Explain StampedLock.
A: StampedLock (Java 8+) provides an "Optimistic Read" mode where threads read without acquiring a true lock, validating afterwards if a write occurred. It is designed to replace ReentrantReadWriteLock (RRWL) in read-heavy workloads.
Why StampedLock was created over RRWL:
public class Point {
private double x, y;
private final StampedLock sl = new StampedLock();
public double distanceFromOrigin() {
// 1. Try an optimistic read lock (returns stamp; zero OS lock / zero CAS)
long stamp = sl.tryOptimisticRead();
// 2. MUST copy shared state into local variables first
double currentX = x;
double currentY = y;
// 3. Validate if a write occurred during the read window
if (!sl.validate(stamp)) {
// Validation failed! Fall back to a pessimistic read lock
stamp = sl.readLock();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX + currentY * currentY);
}
}
Key Limitations:
Q: What is the purpose of ForkJoinPool.commonPool()?
A: It’s a shared, JVM-wide thread pool utilized by Parallel Streams, CompletableFuture (when no executor is supplied), and asynchronous tasks. Submitting heavy I/O-bound blocking tasks to the common pool starves other application components across the entire JVM.
Q: How does Thread.interrupt() actually work?
A: It sets an internal boolean "interrupted status" flag on the target thread. Blocking methods (such as Thread.sleep(), Object.wait(), or LockSupport.park()) continuously poll this flag; when detected, they clear the flag and throw an InterruptedException.
Category 3: Enterprise Integration Patterns (EIP) & ESB
Q: What is a Content-Based Router?
A: An integration pattern where a incoming message is dynamically routed to different downstream destinations based on its content (e.g., evaluating XPath, JSONPath, or Message Header values).
Q: Explain the Idempotent Consumer pattern.
A: Ensures that processing duplicate messages results in identical system state with zero unwanted side effects. Typically implemented by extracting a unique MessageID and maintaining an idempotent repository (e.g., Redis or DB constraint) to filter out previously processed IDs.
Q: What is a Dead Letter Channel (DLQ)?
A: A designated queue or endpoint where messages that repeatedly fail processing after all retry/redelivery attempts are moved for manual inspection, monitoring, and debugging.
Q: Explain the "Claim Check" pattern.
A: Used when dealing with large message payloads (e.g., 50MB files). Instead of passing the massive payload through a message broker (which degrades broker throughput), the payload is stored in an external object store (e.g., AWS S3), and only a reference token ("Claim Check ID") is transmitted through the broker.
Q: How does the "Splitter" pattern handle large XML files?
A: It breaks a single large composite message into multiple smaller, independent sub-messages that can be processed in parallel downstream.
Streaming Parsers (SAX / StAX) & Architectural Mechanics:
Q: What is the "Aggregator" pattern and how do you handle timeouts?
A: The logical inverse of the Splitter. It combines multiple related sub-messages back into a single composite message based on a Correlation ID. Timeouts are handled via a "Completion Strategy" that releases and processes partial results if expected fragments fail to arrive within a defined time window.
Q: Difference between Point-to-Point and Publish-Subscribe.
A:
Q: What is the "Wire Tap" pattern?
A: An integration pattern that intercepts a message from the main pipeline and routes a copy to a secondary destination (e.g., for audit logging, metrics, or wire-level inspection) without modifying or delaying the main message flow.
Q: How do you handle Poison Pill messages in a JMS queue?
A: Configure a Redelivery Policy on the broker. If a message causes an exception and is rolled back times (exceeding the maximum redelivery threshold), the broker automatically diverts the message to a Dead Letter Queue (DLQ).
Q: Explain "Message Translator" pattern.
A: Translates data structures between disparate systems—converting the sender's data protocol into the receiver's expected schema (e.g., mapping incoming XML payloads to JAXB objects, or transforming CSV lines into JSON messages).
Category 4: Spring Boot & EcosystemQ: Explain @SpringBootApplication components.A: It is a meta-annotation that combines three core Spring annotations:
Q: How do you implement a custom FailureAnalyzer in Spring Boot?
A: Extend AbstractFailureAnalyzer<E> and register it in the appropriate Service Provider Interface (SPI) configuration file.
Architectural Purpose & Registration Mechanics:
FailureAnalyzer intercepts startup exceptions (e.g., bad port binding, database auth failure) and converts 100-line nested BeanCreationException stack traces into clean, operational diagnostics:
***************************
APPLICATION FAILED TO START
***************************
Description: The API Key 'INVALID' is invalid or expired.
Action: Provide a valid key in application.properties via 'app.api-key=<KEY>'.
Step-by-Step Implementation:
@Override
protected FailureAnalysis analyze(Throwable rootFailure, InvalidApiKeyException cause) {
String description = "The API Key '" + cause.getApiKey() + "' is invalid.";
String action = "Set a valid key via 'app.api-key' in application.properties.";
return new FailureAnalysis(description, action, cause);
}
}
Q: What is the difference between BeanFactory and ApplicationContext?
A: ApplicationContext is a complete sub-interface of BeanFactory. While BeanFactory provides basic bean creation and explicit dependency wiring engines, ApplicationContext adds enterprise capabilities.
1: Core Java & JDK Internals (Advanced)
Q: How do Virtual Threads (Project Loom) differ from platform threads in terms of memory?
A: Platform threads have a fixed-size stack (typically ~1MB) allocated directly by the Operating System. Virtual threads are managed entirely by the JVM, and their stack frames are stored as objects on the Java Heap, growing and shrinking dynamically as needed.
Q: Explain the 'Happens-Before' relationship in the Java Memory Model.
A: It’s a formal guarantee that memory writes by one specific statement are guaranteed to be visible to another specific statement in another thread. For example, a write to a volatile field happens-before every subsequent read of that same field.
Q: Why is invokedynamic important for Java 8+?
A: It allows the JVM to delay the binding of a method call until runtime. This was essential for implementing Lambdas efficiently without creating thousands of synthetic anonymous .class files on disk during compilation.
Q: How does the G1 Garbage Collector handle "Humongous Objects"?
A: Objects larger than 50% of a G1 region size are designated as "Humongous." They are allocated in special contiguous sequences of regions directly in the Old Generation and can be reclaimed during the cleanup phase or a Full GC.
Q: What are Scoped Values (JEP 446)?
A: A modern alternative to ThreadLocal, designed specifically for Virtual Threads. They allow sharing immutable data across a large number of threads with lower memory overhead, zero footprint leak risks, and a clear, lexically bounded lifecycle.
Q: Explain the difference between poll() and epoll in the context of Java NIO.
A:
- poll() (): The kernel scans every registered file descriptor to check for active events. It is linear and becomes a severe CPU bottleneck as connection counts grow.
- epoll (): Linux-specific. It uses a callback mechanism in the kernel. When network hardware notifies the kernel of events, ready descriptors are placed into a "Ready List." The CPU only processes active sockets, making it the backbone of scalable net I/O frameworks like Netty.
- Note on Disk Files: epoll and Selectors are for sockets and pipes. Standard FileChannel is not "selectable" because disk files are technically always considered "ready" by the OS kernel (data access is managed asynchronously via the Page Cache).
Q: What is "False Sharing" and how does @Contended fix it?
A: False Sharing occurs when two threads running on different CPU cores modify distinct variables that happen to reside on the same 64-byte CPU cache line. Writes by one core invalidate the entire cache line for the other core, causing severe cache-line bouncing. @Contended inserts automatic memory padding around fields to force them onto separate cache lines.
Q: How would you detect a deadlock programmatically in a running JVM?
A: Use ThreadMXBean.findDeadlockedThreads().
Q: What is the difference between Strong, Soft, Weak, and Phantom references?
A:
- Strong: Default references. Never GC’d while reachable.
- Soft: GC’d only as a last resort before an OutOfMemoryError occurs (ideal for memory-sensitive caches).
- Weak: GC’d at the very next garbage collection cycle regardless of memory pressure (ideal for WeakHashMap keys).
- Phantom: Enqueued in a ReferenceQueue after the object is physically finalized; used for post-mortem resource cleanup without resurrection risks.
Q: How does String.intern() work in Java 17+?
A: It checks the global String Constant Pool. If the string exists, it returns the reference; otherwise, it adds the string to the pool. Since Java 7, the pool resides in the main Heap (not PermGen/Metaspace), allowing interned strings to be garbage collected if no longer referenced.
Category 2: Concurrency & Multithreading
Q: Compare synchronized vs ReentrantLock.
A: ReentrantLock offers advanced features like fairness selection, non-blocking lock acquisition (tryLock()), interruptible lock waits, and multiple Condition objects. synchronized is simpler, managed at the language/bytecode level, and automatically optimized by the JVM runtime (e.g., lock coarsen/elision).
Q: What is a CompletableFuture and how does it handle exceptions?
A: It’s a non-blocking, composable Future for asynchronous programming. Exceptions are propagated down the execution pipeline and handled gracefully via .exceptionally() or .handle(), allowing recovery or fallback execution.
Q: How does LongAdder outperform AtomicLong under high contention?
A: AtomicLong uses a single shared CAS (Compare-And-Swap) variable; under high thread contention, most threads spin endlessly failing CAS updates. LongAdder maintains a dynamic array of internal Cell objects to distribute increment operations across threads, summing them up when .sum() is called.
Q: Explain Phaser vs CyclicBarrier vs CountDownLatch.
A:
- CountDownLatch: One-time gate. Threads wait until a counter hits zero. It cannot be reset or reused.
- CyclicBarrier: Fixed-set synchronization point where a predetermined number of threads must meet before proceeding. Reusable across cycles.
- Phaser: Dynamic orchestration tool where threads can register, deregister, and advance through multiple sequential phases on the fly.
Q: What is the "Thundering Herd" problem in thread pools?
A: Occurs when a large number of waiting threads are woken up simultaneously to handle a task event, but only one thread can claim the task while the rest go back to sleep, causing excessive CPU context-switching spikes. Proper queue orchestration in ThreadPoolExecutor mitigates this.
Q: How would you implement a Rate Limiter vs Concurrency Limiter using Semaphore?A:
- Concurrency Limiter: Thread calls semaphore.acquire(), performs work, and invokes semaphore.release() inside a finally block. Limits active concurrent executions.
- Rate Limiter: Thread calls semaphore.acquire() before work. A separate background scheduler thread invokes semaphore.release() at fixed calendar intervals (e.g., every 100ms). Limits total transactions per second (TPS).
Q: Why should you avoid Executors.newFixedThreadPool(n) for high-throughput apps?
A: Executors.newFixedThreadPool(n) uses an unbounded LinkedBlockingQueue (default capacity = Integer.MAX_VALUE).
Deep Dive & Internal Mechanics:
When you create a fixed thread pool, the JVM instantiates a ThreadPoolExecutor with corePoolSize = n and maximumPoolSize = n:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(
nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>() // Unbounded Queue!
);
}
- maximumPoolSize is Useless: The executor only creates non-core threads when its work queue is full. Since an unbounded queue never fills up, the pool will never scale past n threads.
- Rejection Policy Never Triggers: The AbortPolicy is never reached.
- OutOfMemoryError (OOM): If tasks arrive at 10,000 req/sec but worker threads can only process 2,000 req/sec, pending tasks stack up endlessly on the JVM heap. Each task holds references to request contexts and data buffers, eventually triggering java.lang.OutOfMemoryError: Java heap space.
- GC Thrashing: Tens of thousands of pending tasks survive long enough to migrate into the Old Generation, causing catastrophic Full GC pauses. Furthermore, LinkedBlockingQueue allocates an internal Node wrapper object for every single task enqueued, adding extra memory overhead.
Production Solution:
Always construct explicit ThreadPoolExecutor instances with bounded queues and an explicit backpressure rejection policy:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
coreThreads, maxThreads, 60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000), // Bounded Queue
new ThreadPoolExecutor.CallerRunsPolicy() // Backpressure strategy
);
Q: Explain StampedLock.
A: StampedLock (Java 8+) provides an "Optimistic Read" mode where threads read without acquiring a true lock, validating afterwards if a write occurred. It is designed to replace ReentrantReadWriteLock (RRWL) in read-heavy workloads.
Why StampedLock was created over RRWL:
- Avoid Writer Starvation: RRWL can starve writer threads if a continuous stream of reader threads keeps the read lock acquired.
- Eliminate Reader CAS Overhead: In RRWL, every reader atomically updates a shared lock counter using expensive CAS operations, leading to CPU cache-line bouncing across cores.
public class Point {
private double x, y;
private final StampedLock sl = new StampedLock();
public double distanceFromOrigin() {
// 1. Try an optimistic read lock (returns stamp; zero OS lock / zero CAS)
long stamp = sl.tryOptimisticRead();
// 2. MUST copy shared state into local variables first
double currentX = x;
double currentY = y;
// 3. Validate if a write occurred during the read window
if (!sl.validate(stamp)) {
// Validation failed! Fall back to a pessimistic read lock
stamp = sl.readLock();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX + currentY * currentY);
}
}
Key Limitations:
- Non-Reentrant: StampedLock is not reentrant! A thread holding a write lock will deadlock itself if it attempts to acquire the write lock again.
- Local Copy Rule: Shared fields must be copied to local stack variables before sl.validate() is invoked to avoid word tearing or inconsistent state reads.
Q: What is the purpose of ForkJoinPool.commonPool()?
A: It’s a shared, JVM-wide thread pool utilized by Parallel Streams, CompletableFuture (when no executor is supplied), and asynchronous tasks. Submitting heavy I/O-bound blocking tasks to the common pool starves other application components across the entire JVM.
Q: How does Thread.interrupt() actually work?
A: It sets an internal boolean "interrupted status" flag on the target thread. Blocking methods (such as Thread.sleep(), Object.wait(), or LockSupport.park()) continuously poll this flag; when detected, they clear the flag and throw an InterruptedException.
Category 3: Enterprise Integration Patterns (EIP) & ESB
Q: What is a Content-Based Router?
A: An integration pattern where a incoming message is dynamically routed to different downstream destinations based on its content (e.g., evaluating XPath, JSONPath, or Message Header values).
Q: Explain the Idempotent Consumer pattern.
A: Ensures that processing duplicate messages results in identical system state with zero unwanted side effects. Typically implemented by extracting a unique MessageID and maintaining an idempotent repository (e.g., Redis or DB constraint) to filter out previously processed IDs.
Q: What is a Dead Letter Channel (DLQ)?
A: A designated queue or endpoint where messages that repeatedly fail processing after all retry/redelivery attempts are moved for manual inspection, monitoring, and debugging.
Q: Explain the "Claim Check" pattern.
A: Used when dealing with large message payloads (e.g., 50MB files). Instead of passing the massive payload through a message broker (which degrades broker throughput), the payload is stored in an external object store (e.g., AWS S3), and only a reference token ("Claim Check ID") is transmitted through the broker.
- Trade-off: Protects broker memory but incurs a "Network Tax" (additional HTTP/S3 fetches for consumers).
- Optimization: Combine with an eTag. The consumer presents its local cached payload hash; if the remote eTag matches, the consumer skips downloading the 50MB payload altogether.
Q: How does the "Splitter" pattern handle large XML files?
A: It breaks a single large composite message into multiple smaller, independent sub-messages that can be processed in parallel downstream.
Streaming Parsers (SAX / StAX) & Architectural Mechanics:
- The Pattern vs. Tool: The Splitter is the architectural pattern (what to do); SAX/StAX are the parsing tools (how to do it without hitting OOM).
- SAX (Simple API for XML - Push): Reads XML linearly start-to-finish as an event stream (startElement, endElement). Highly memory-efficient because it never loads the DOM tree into memory.
- StAX (Streaming API for XML - Pull): Allows the application to explicitly pull events (reader.next()) from the stream. StAX is superior for backpressure because the consumer controls the pace of parsing.
- The "Huge Element" Poison Pill: If an XML file contains a single, non-delimited 500MB <Order> tag, even SAX/StAX will struggle if mapped into a Java object. Solutions include recursive splitting at deeper child elements, using streaming pull parsers, and enforcing XML schemas favoring "shallow and wide" structures over deep/bloated nodes.
Q: What is the "Aggregator" pattern and how do you handle timeouts?
A: The logical inverse of the Splitter. It combines multiple related sub-messages back into a single composite message based on a Correlation ID. Timeouts are handled via a "Completion Strategy" that releases and processes partial results if expected fragments fail to arrive within a defined time window.
Q: Difference between Point-to-Point and Publish-Subscribe.
A:
- Point-to-Point (Queues): Guarantees that each message is processed by exactly one consumer (Competing Consumers pattern).
- Publish-Subscribe (Topics): Broadcasts every message to all active, registered subscribers.
Q: What is the "Wire Tap" pattern?
A: An integration pattern that intercepts a message from the main pipeline and routes a copy to a secondary destination (e.g., for audit logging, metrics, or wire-level inspection) without modifying or delaying the main message flow.
Q: How do you handle Poison Pill messages in a JMS queue?
A: Configure a Redelivery Policy on the broker. If a message causes an exception and is rolled back times (exceeding the maximum redelivery threshold), the broker automatically diverts the message to a Dead Letter Queue (DLQ).
Q: Explain "Message Translator" pattern.
A: Translates data structures between disparate systems—converting the sender's data protocol into the receiver's expected schema (e.g., mapping incoming XML payloads to JAXB objects, or transforming CSV lines into JSON messages).
Category 4: Spring Boot & EcosystemQ: Explain @SpringBootApplication components.A: It is a meta-annotation that combines three core Spring annotations:
- @Configuration: Marks the class as a source of bean definitions.
- @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings.
- @ComponentScan: Scans the current package and sub-packages for @Component, @Service, @Repository, and @Controller classes.
Q: How do you implement a custom FailureAnalyzer in Spring Boot?
A: Extend AbstractFailureAnalyzer<E> and register it in the appropriate Service Provider Interface (SPI) configuration file.
Architectural Purpose & Registration Mechanics:
FailureAnalyzer intercepts startup exceptions (e.g., bad port binding, database auth failure) and converts 100-line nested BeanCreationException stack traces into clean, operational diagnostics:
***************************
APPLICATION FAILED TO START
***************************
Description: The API Key 'INVALID' is invalid or expired.
Action: Provide a valid key in application.properties via 'app.api-key=<KEY>'.
Step-by-Step Implementation:
- Extend AbstractFailureAnalyzer:
@Override
protected FailureAnalysis analyze(Throwable rootFailure, InvalidApiKeyException cause) {
String description = "The API Key '" + cause.getApiKey() + "' is invalid.";
String action = "Set a valid key via 'app.api-key' in application.properties.";
return new FailureAnalysis(description, action, cause);
}
}
- Register via SPI File:
- Spring Boot 2.7+ & Boot 3.x (Modern Standard): Create src/main/resources/META-INF/spring/org.springframework.boot.diagnostics.FailureAnalyzer containing the fully qualified class name:
com.example.diagnostics.InvalidApiKeyFailureAnalyzer - Spring Boot 2.6 and earlier (Legacy): Register in src/main/resources/META-INF/spring.factories under key org.springframework.boot.diagnostics.FailureAnalyzer.
- Spring Boot 2.7+ & Boot 3.x (Modern Standard): Create src/main/resources/META-INF/spring/org.springframework.boot.diagnostics.FailureAnalyzer containing the fully qualified class name:
- Stack Trace Noise: Unhandled startup exceptions are wrapped in multiple layers of BeanCreationException, burying raw exception messages under 100+ lines of framework logs.
- Decoupling: Decouples core business/domain exception logic from operational, user-facing diagnostic formatting.
- Third-Party Exception Handling: Allows developers to write custom startup failure diagnostics for 3rd-party library exceptions (e.g., HikariCP connection pool timeouts or Jackson JSON parsing errors) whose source code cannot be edited.
Q: What is the difference between BeanFactory and ApplicationContext?
A: ApplicationContext is a complete sub-interface of BeanFactory. While BeanFactory provides basic bean creation and explicit dependency wiring engines, ApplicationContext adds enterprise capabilities.
Q: How does @Transactional work internally?
A: Spring uses AOP (Aspect-Oriented Programming) to build a dynamic proxy around the bean. When a @Transactional method is called, the proxy intercepts the call, opens a database connection/transaction via PlatformTransactionManager, executes the actual method, and automatically performs a commit() or rollback() based on thrown runtime exceptions.
1. How @Transactional Works Internally
Q: What is "Bean Definition Overriding" and why is it disabled by default in Spring Boot 2.1+?
A: It allowed a bean definition to automatically overwrite an existing bean registered with the exact same name. It was disabled by default (spring.main.allow-bean-definition-overriding=false) to prevent accidental bean shadowing bugs across large teams, making configuration errors fail fast during application startup.
Q: How do you handle circular dependencies in Spring?
A: The primary resolution is refactoring code to adhere to the Single Responsibility Principle. If refactoring isn't immediate, resolve it via @Lazy injection on constructors or setter injection.
Q: Explain @ConditionalOnProperty.
A: Allows Spring beans or auto-configurations to be conditionally loaded into the ApplicationContext only if a specified configuration property is defined and matches an expected value.
Q: Difference between WebClient and RestTemplate.
A: RestTemplate is a synchronous, blocking HTTP client (now in maintenance mode). WebClient (part of spring-webflux) is a modern, non-blocking, reactive client supporting both synchronous and streaming HTTP paradigms.
Q: How do you secure a Spring Boot Actuator endpoint?
A: Restrict access via Spring Security by scoping request matchers to actuator paths:
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth.hasRole("ADMIN"));
Q: What is the purpose of spring-boot-starter-parent?
A: Acts as a parent POM in Maven, providing curated dependency version management (BOM), default plugin configurations (like the spring-boot-maven-plugin), and resource filtering defaults.
Category 5: Data Persistence (SQL, Hibernate, Sybase)
Q: Explain the Hibernate "N+1" problem and how to solve it.
A: Occurs when fetching 1 parent entity with child associations results in executing 1 initial query for the parent followed by separate SQL queries to load each child association.
Q: How do you optimize a query in Sybase/SQL Server?
A: Analyze the Execution Plan (SET SHOWPLAN ON), build proper covered indexes, ensure predicates are SARGable (Search Argumentable - e.g., avoiding function calls like WHERE YEAR(date) = 2026 on indexed columns), and eliminate unnecessary SELECT * fetches.
Q: What is the difference between list() and iterate() in Hibernate?
A:
Q: Explain Session.get() vs Session.load() (find() vs getReference()).
A: Spring uses AOP (Aspect-Oriented Programming) to build a dynamic proxy around the bean. When a @Transactional method is called, the proxy intercepts the call, opens a database connection/transaction via PlatformTransactionManager, executes the actual method, and automatically performs a commit() or rollback() based on thrown runtime exceptions.
1. How @Transactional Works Internally
- Dynamic Proxy (AOP): Spring wraps your bean in a proxy. When a @Transactional method is called, the proxy intercepts it, fetches a database connection from PlatformTransactionManager, and binds it to the current thread via ThreadLocal.
- Execution & Lifecycle: The proxy executes the target method and handles completion:
- Success: Calls connection.commit().
- Failure: Triggers connection.rollback() for unchecked exceptions (RuntimeException / Error). Standard checked exceptions commit by default unless configured with rollbackFor.
- State Check: Spring does not blindly flip autocommit. It checks connection.getAutoCommit() first.
- Disabling: If autocommit is true, Spring disables it (setAutoCommit(false)) to start the transaction block.
- Restoration: When the transaction ends, Spring checks if it modified autocommit. If yes, it restores autoCommit(true) before returning the connection to the pool.
- Context Loss: Spring stores transaction state in a ThreadLocal variable. A child thread spawned inside a transaction block gets an empty ThreadLocal context and will obtain a separate database connection (Connection B).
- Consequences:
- The child operates outside the parent's transaction boundary.
- Child writes commit independently and cannot roll back if the parent transaction fails.
- Data Visibility (Isolation Levels):
- Under READ UNCOMMITTED, the child thread performs a dirty read of the parent's uncommitted data.
- Under standard isolation levels (READ COMMITTED, REPEATABLE READ), the child thread reads older, committed data or blocks waiting for row locks held by the parent.
Q: What is "Bean Definition Overriding" and why is it disabled by default in Spring Boot 2.1+?
A: It allowed a bean definition to automatically overwrite an existing bean registered with the exact same name. It was disabled by default (spring.main.allow-bean-definition-overriding=false) to prevent accidental bean shadowing bugs across large teams, making configuration errors fail fast during application startup.
Q: How do you handle circular dependencies in Spring?
A: The primary resolution is refactoring code to adhere to the Single Responsibility Principle. If refactoring isn't immediate, resolve it via @Lazy injection on constructors or setter injection.
Q: Explain @ConditionalOnProperty.
A: Allows Spring beans or auto-configurations to be conditionally loaded into the ApplicationContext only if a specified configuration property is defined and matches an expected value.
Q: Difference between WebClient and RestTemplate.
A: RestTemplate is a synchronous, blocking HTTP client (now in maintenance mode). WebClient (part of spring-webflux) is a modern, non-blocking, reactive client supporting both synchronous and streaming HTTP paradigms.
Q: How do you secure a Spring Boot Actuator endpoint?
A: Restrict access via Spring Security by scoping request matchers to actuator paths:
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.authorizeHttpRequests(auth -> auth.hasRole("ADMIN"));
Q: What is the purpose of spring-boot-starter-parent?
A: Acts as a parent POM in Maven, providing curated dependency version management (BOM), default plugin configurations (like the spring-boot-maven-plugin), and resource filtering defaults.
Category 5: Data Persistence (SQL, Hibernate, Sybase)
Q: Explain the Hibernate "N+1" problem and how to solve it.
A: Occurs when fetching 1 parent entity with child associations results in executing 1 initial query for the parent followed by separate SQL queries to load each child association.
- Solutions: Use JOIN FETCH in JPQL/HQL, utilize @EntityGraph, set @BatchSize(size = 20), or fetch via DTO projections.
- L1 Cache: Session-scoped, mandatory, and enabled by default. Flushed when the Hibernate Session closes.
- L2 Cache: SessionFactory-scoped, optional, and shared across all sessions/threads in the application (e.g., using Ehcache or Redis integrations).
- Pessimistic Locking: Locks the database row at the database level (SELECT ... FOR UPDATE). Prevents concurrent reads/writes entirely; used for high-conflict financial operations.
- Optimistic Locking: Does not lock rows on the DB. Uses an integer or timestamp @Version column. On update, executes WHERE id = ? AND version = old_version. If another transaction updated the row first, an OptimisticLockException is thrown.
Q: How do you optimize a query in Sybase/SQL Server?
A: Analyze the Execution Plan (SET SHOWPLAN ON), build proper covered indexes, ensure predicates are SARGable (Search Argumentable - e.g., avoiding function calls like WHERE YEAR(date) = 2026 on indexed columns), and eliminate unnecessary SELECT * fetches.
Q: What is the difference between list() and iterate() in Hibernate?
A:
- list(): Executes a single SQL query returning all matching database entities immediately.
- iterate(): Executes an initial query selecting only the entity primary keys (IDs). It then issues individual SQL queries to fetch entity fields on demand (useful if entities are already populated in the L2 cache).
Q: Explain Session.get() vs Session.load() (find() vs getReference()).
Architectural Advantage of Session.load():
Avoids unnecessary SELECT queries when assigning foreign keys to new entities:
// NO SELECT query executed! Creates dummy proxy holding user_id = 42
User userProxy = session.load(User.class, 42);
Order order = new Order();
order.setUser(userProxy); // FK assignment only requires the user_id integer!
session.save(order); // Issues single INSERT INTO orders (user_id) VALUES (42)
Q: Explain ACID properties.
A: Atomicity (all operations succeed or all rollback), Consistency (data transitions from one valid state to another), Isolation (concurrent transactions do not interfere with each other), Durability (committed changes survive system crashes).
Q: What are the different Transaction Isolation Levels?
A:
Q: How does "Dirty Read" occur?
A: When Transaction A reads modified data from a row that has been written by Transaction B, but Transaction B has not yet committed. If Transaction B subsequently rolls back, Transaction A worked with uncommitted, non-existent data.
Q: What is a "Phantom Read"?
A: Occurs when Transaction A executes a range query (e.g., WHERE age > 30) twice within the same transaction, but receives a different number of rows because Transaction B inserted or deleted rows matching the range criteria in the interim.
Q: How do you use Liquibase for DB migrations?
A: Database schema changes are defined in version-controlled Changelog files (XML/YAML/SQL) as discrete changeSet blocks. Liquibase executes unapplied changesets against target databases and tracks execution state in a dedicated DATABASECHANGELOG table.
Category 6: Algorithms & Performance Optimization
Q: Implement a Thread-Safe Singleton without the synchronized keyword.
A: Use an Enum or the Initialization-on-demand Holder idiom:
public class Singleton {
private Singleton() {}
private static class InstanceHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
}
Q: How would you find the first non-repeating character in a large stream of strings?
A: Use a LinkedHashMap to maintain insertion order alongside character frequency counts, or use a custom doubly-linked list combined with a HashMap for lookups and removal.
Q: Write a code snippet to reverse a Linked List.
A: Iteratively flip pointers using prev, curr, and next references in time and auxiliary space:
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
Q: How do you implement a Producer-Consumer pattern using BlockingQueue?
A: Producers invoke queue.put(item) (blocks when the queue capacity is full); consumers invoke queue.take() (blocks when the queue is empty).
Q: Explain the "Two-Pointer" technique.
A: An algorithmic strategy using two array indices/references that traverse a sequence simultaneously (e.g., one moving from left-to-right and the other right-to-left) to find target pairs, reverse arrays, or detect cycles in time.
Q: How does a HashMap handle collisions in Java 8+?
A: Elements with matching hash buckets are stored in a singly linked list. If a bucket's collision count exceeds a threshold (treeify threshold = 8) and total map capacity , the bucket automatically converts from a linked list into a self-balancing Red-Black Tree, reducing lookup complexity from to .
Q: Compare Dual-Pivot Quicksort vs Timsort.
A: Both are default JDK sorting implementations, but optimized for completely different memory layouts and data constraints.
Avoids unnecessary SELECT queries when assigning foreign keys to new entities:
// NO SELECT query executed! Creates dummy proxy holding user_id = 42
User userProxy = session.load(User.class, 42);
Order order = new Order();
order.setUser(userProxy); // FK assignment only requires the user_id integer!
session.save(order); // Issues single INSERT INTO orders (user_id) VALUES (42)
Q: Explain ACID properties.
A: Atomicity (all operations succeed or all rollback), Consistency (data transitions from one valid state to another), Isolation (concurrent transactions do not interfere with each other), Durability (committed changes survive system crashes).
Q: What are the different Transaction Isolation Levels?
A:
- READ UNCOMMITTED: Allows dirty reads, non-repeatable reads, phantom reads.
- READ COMMITTED: Prevents dirty reads. Allows non-repeatable and phantom reads.
- REPEATABLE READ: Prevents dirty and non-repeatable reads. Allows phantom reads.
- SERIALIZABLE: Prevents all concurrency anomalies; executes transactions sequentially.
Q: How does "Dirty Read" occur?
A: When Transaction A reads modified data from a row that has been written by Transaction B, but Transaction B has not yet committed. If Transaction B subsequently rolls back, Transaction A worked with uncommitted, non-existent data.
Q: What is a "Phantom Read"?
A: Occurs when Transaction A executes a range query (e.g., WHERE age > 30) twice within the same transaction, but receives a different number of rows because Transaction B inserted or deleted rows matching the range criteria in the interim.
Q: How do you use Liquibase for DB migrations?
A: Database schema changes are defined in version-controlled Changelog files (XML/YAML/SQL) as discrete changeSet blocks. Liquibase executes unapplied changesets against target databases and tracks execution state in a dedicated DATABASECHANGELOG table.
Category 6: Algorithms & Performance Optimization
Q: Implement a Thread-Safe Singleton without the synchronized keyword.
A: Use an Enum or the Initialization-on-demand Holder idiom:
public class Singleton {
private Singleton() {}
private static class InstanceHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return InstanceHolder.INSTANCE;
}
}
Q: How would you find the first non-repeating character in a large stream of strings?
A: Use a LinkedHashMap to maintain insertion order alongside character frequency counts, or use a custom doubly-linked list combined with a HashMap for lookups and removal.
Q: Write a code snippet to reverse a Linked List.
A: Iteratively flip pointers using prev, curr, and next references in time and auxiliary space:
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
Q: How do you implement a Producer-Consumer pattern using BlockingQueue?
A: Producers invoke queue.put(item) (blocks when the queue capacity is full); consumers invoke queue.take() (blocks when the queue is empty).
Q: Explain the "Two-Pointer" technique.
A: An algorithmic strategy using two array indices/references that traverse a sequence simultaneously (e.g., one moving from left-to-right and the other right-to-left) to find target pairs, reverse arrays, or detect cycles in time.
Q: How does a HashMap handle collisions in Java 8+?
A: Elements with matching hash buckets are stored in a singly linked list. If a bucket's collision count exceeds a threshold (treeify threshold = 8) and total map capacity , the bucket automatically converts from a linked list into a self-balancing Red-Black Tree, reducing lookup complexity from to .
Q: Compare Dual-Pivot Quicksort vs Timsort.
A: Both are default JDK sorting implementations, but optimized for completely different memory layouts and data constraints.
Why Dual-Pivot Quicksort for Primitives?
Primitive values (int, long) are stored contiguously in memory. Because primitives carry zero object pointer overhead and comparing two numbers takes 1 CPU cycle, Dual-Pivot Quicksort partitions arrays into 3 sections using 2 pivots (). This maximizes CPU cache-line efficiency and minimizes element swaps in-place without allocating extra memory.
Why Timsort for Objects?
Objects in Java require stability (e.g., sorting employees by Age, then Name). Additionally, invoking custom Comparator or compareTo() methods incurs method-call overhead. Timsort is an adaptive hybrid algorithm (Merge Sort + Insertion Sort) that identifies pre-sorted sequences ("runs") in data, operating in time on partially sorted datasets while guaranteeing mathematical stability.
Q: How would you process a 10GB file in a JVM with only 2GB RAM?
A: Avoid reading the whole file into memory. Stream the file using a BufferedReader, Java Streams via Files.lines(), or map chunks using MappedByteBuffer (Java NIO) to iterate through memory-mapped file channels line-by-line.
Category 7: Infrastructure, CI/CD, Linux & DevOps
Q: What is a "Blue-Green" deployment?
A: A zero-downtime release strategy involving two identical production environments. One environment (Green) actively handles live user traffic, while updates are deployed and tested in the idle environment (Blue). Once validated, router/load-balancer traffic is switched instantly to Blue.
Q: How do you find which process is using port 8080 in Linux?
A: lsof -i :8080 or netstat -tulpn | grep 8080.
Q: Difference between kill -9 and kill -15.
A:
Q: Explain the role of SonarQube in CI/CD.
A: Performs automated static code analysis during automated build pipelines to detect security vulnerabilities, code smells, duplicate code blocks, and maintainability issues, enforcing Quality Gates before merging.
Q: What is "Jenkins Pipeline as Code"?
A: Defining the complete CI/CD build, test, and deployment steps programmatically inside a Jenkinsfile stored directly alongside the source code in version control.
Q: How do you debug a java.lang.OutOfMemoryError: Metaspace?
A: Metaspace stores class metadata. Debug by analyzing heap dumps via MAT (Memory Analyzer Tool) for classloader leaks (common with dynamic proxy generation or hot-reloading frameworks), and temporarily increase limit via -XX:MaxMetaspaceSize.
Q: What is the purpose of a Maven "BOM" (Bill of Materials)?
A: A special POM file that centralizes dependency version management across sub-modules or multi-repo projects, allowing downstream projects to declare dependencies without specifying explicit version tags.
Q: How does Docker differ from a Virtual Machine?
A: Virtual Machines virtualize hardware layers and run a full Guest Operating System on top of a Hypervisor. Docker containerizes applications at the OS level, sharing the host OS kernel directly, resulting in lightweight startup times (milliseconds) and low memory overhead.
Q: Explain grep, sed, and awk use cases.
A:
Q: How do you check the last 100 lines of a log file dynamically?
A: tail -f -n 100 application.log.
Category 8: Messaging & Distributed TransactionsQ: What is a 2-Phase Commit (2PC)?A: A consensus protocol for distributed database transactions across multiple nodes consisting of:
Q: Why is 2PC considered "slow" or "blocking"?
A: 2PC is a blocking protocol. If the coordinator or any participant crashes during the Prepared state, all participating database instances must hold locks on dirty resources indefinitely until recovery completes, destroying throughput.
Q: What is the SAGA pattern?
A: An alternative to 2PC for microservices. It decomposes a distributed transaction into a sequence of local service transactions. Each step updates a local database; if a step fails, the Saga executes a series of Compensating Transactions in reverse order to undo prior changes.
Q: What is "Backpressure" in integration?
A: A mechanism where an overwhelmed consumer actively signals a producer to slow down or halt its message dispatch rate.
+-----------------------------+
| Requires Feedback Loop |
+-----------------------------+
/ \
/ \
v v
[ Reactive Streams ] [ Unthrottled Broadcast ]
- Consumer calls `request(n)` - No feedback channel possible
- Producer pushes EXACTLY n items - Fast producer overwhelms consumer
- Example: Netflix DASH Video - Result: Packet drop or OOM
Backpressure Classification across Architectures:
Q: Explain "Competing Consumers" pattern.
A: Attaching multiple consumer instances to a single message queue. The queue broker ensures each incoming message is delivered to only one consumer, enabling parallel processing and high-throughput execution.
Q: What is JTA (Java Transaction API)?
A: A standard Java EE/Jakarta specification that enables applications to manage distributed transactions across multiple XA-compliant resource managers (e.g., coordinating a transaction between a PostgreSQL DB and an IBM MQ broker).
Category 9: Testing & Quality (TDD/BDD)Q: Difference between Mock and Spy in Mockito.A:
Q: What is "Mutation Testing"?
A: A fault-based testing technique where a tool (like PITest) mutates source code operators (e.g., changing a + b to a - b, or flipping > to <). If your unit test suite continues to pass despite the code mutation, the test survived—indicating weak assertions or inadequate coverage.
Q: Explain @ParameterizedTest in JUnit 5.
A: Enables running a single test method repeatedly with different arguments (supplied via @ValueSource, @CsvSource, or @MethodSource).
Q: How do you test private methods?
A: You shouldn't test private methods directly. Test them through the public API methods that invoke them.
The Architectural Philosophy:
Private methods are implementation details, not API contracts. Tests must focus on behavior (what a class does), not implementation (how it does it).
Category 10: Performance & Modern Java (Java 17 to 25 Focus)
Q: What is "Application Class Data Sharing" (AppCDS)?
A: Reduces JVM startup time and memory footprint by pre-parsing and dumping class metadata into an archived .jsa file during build time, which can be memory-mapped across multiple running JVM processes.
Q: Explain Sealed Classes (Java 17).
A: Restricts which classes or interfaces may extend or implement them using the permits keyword, providing compile-time control over inheritance hierarchies and facilitating exhaustive pattern matching.
public sealed interface Shape permits Circle, Rectangle {}
Q: What are "Records" in Java 14+?
A: Immutable nominal tuple data carriers. The compiler automatically generates final fields, canonical constructors, equals(), hashCode(), and toString() implementations.
Q: What is the SequencedCollection interface in Java 21?
A: A core collection interface introducing a unified API for accessing first and last elements, and retrieving reversed views across ordered collections (e.g., List, Deque, LinkedHashSet). Methods include getFirst(), getLast(), addFirst(), addLast(), and reversed().
Q: Explain ZGC (Z Garbage Collector).
A: A concurrent, low-latency garbage collector designed to handle heaps scaling from megabytes to 16 Terabytes with sub-millisecond pause times by using colored pointers and load barriers.
Category 11: Protocol Architecture Decision Matrix
Primitive values (int, long) are stored contiguously in memory. Because primitives carry zero object pointer overhead and comparing two numbers takes 1 CPU cycle, Dual-Pivot Quicksort partitions arrays into 3 sections using 2 pivots (). This maximizes CPU cache-line efficiency and minimizes element swaps in-place without allocating extra memory.
Why Timsort for Objects?
Objects in Java require stability (e.g., sorting employees by Age, then Name). Additionally, invoking custom Comparator or compareTo() methods incurs method-call overhead. Timsort is an adaptive hybrid algorithm (Merge Sort + Insertion Sort) that identifies pre-sorted sequences ("runs") in data, operating in time on partially sorted datasets while guaranteeing mathematical stability.
Q: How would you process a 10GB file in a JVM with only 2GB RAM?
A: Avoid reading the whole file into memory. Stream the file using a BufferedReader, Java Streams via Files.lines(), or map chunks using MappedByteBuffer (Java NIO) to iterate through memory-mapped file channels line-by-line.
Category 7: Infrastructure, CI/CD, Linux & DevOps
Q: What is a "Blue-Green" deployment?
A: A zero-downtime release strategy involving two identical production environments. One environment (Green) actively handles live user traffic, while updates are deployed and tested in the idle environment (Blue). Once validated, router/load-balancer traffic is switched instantly to Blue.
Q: How do you find which process is using port 8080 in Linux?
A: lsof -i :8080 or netstat -tulpn | grep 8080.
Q: Difference between kill -9 and kill -15.
A:
- kill -15 (SIGTERM): Graceful shutdown request. The process can catch the signal, flush buffers, release file handles/DB locks, and terminate safely.
- kill -9 (SIGKILL): Immediate process termination forced by the OS kernel. The process cannot catch or ignore it; memory and file handles are aborted abruptly without cleanup.
Q: Explain the role of SonarQube in CI/CD.
A: Performs automated static code analysis during automated build pipelines to detect security vulnerabilities, code smells, duplicate code blocks, and maintainability issues, enforcing Quality Gates before merging.
Q: What is "Jenkins Pipeline as Code"?
A: Defining the complete CI/CD build, test, and deployment steps programmatically inside a Jenkinsfile stored directly alongside the source code in version control.
Q: How do you debug a java.lang.OutOfMemoryError: Metaspace?
A: Metaspace stores class metadata. Debug by analyzing heap dumps via MAT (Memory Analyzer Tool) for classloader leaks (common with dynamic proxy generation or hot-reloading frameworks), and temporarily increase limit via -XX:MaxMetaspaceSize.
Q: What is the purpose of a Maven "BOM" (Bill of Materials)?
A: A special POM file that centralizes dependency version management across sub-modules or multi-repo projects, allowing downstream projects to declare dependencies without specifying explicit version tags.
Q: How does Docker differ from a Virtual Machine?
A: Virtual Machines virtualize hardware layers and run a full Guest Operating System on top of a Hypervisor. Docker containerizes applications at the OS level, sharing the host OS kernel directly, resulting in lightweight startup times (milliseconds) and low memory overhead.
Q: Explain grep, sed, and awk use cases.
A:
- grep: Searching and filtering text using regular expressions.
- sed: Stream Editor for transforming or replacing text in-place within streams/files.
- awk: Powerful pattern-scanning and field-processing language (ideal for parsing column-based log files).
Q: How do you check the last 100 lines of a log file dynamically?
A: tail -f -n 100 application.log.
Category 8: Messaging & Distributed TransactionsQ: What is a 2-Phase Commit (2PC)?A: A consensus protocol for distributed database transactions across multiple nodes consisting of:
- Prepare Phase: A Coordinator asks all participating nodes if they are ready to commit.
- Commit Phase: If all participants vote "YES", the coordinator issues a global Commit. If any vote "NO", a global Rollback is issued.
Q: Why is 2PC considered "slow" or "blocking"?
A: 2PC is a blocking protocol. If the coordinator or any participant crashes during the Prepared state, all participating database instances must hold locks on dirty resources indefinitely until recovery completes, destroying throughput.
Q: What is the SAGA pattern?
A: An alternative to 2PC for microservices. It decomposes a distributed transaction into a sequence of local service transactions. Each step updates a local database; if a step fails, the Saga executes a series of Compensating Transactions in reverse order to undo prior changes.
Q: What is "Backpressure" in integration?
A: A mechanism where an overwhelmed consumer actively signals a producer to slow down or halt its message dispatch rate.
+-----------------------------+
| Requires Feedback Loop |
+-----------------------------+
/ \
/ \
v v
[ Reactive Streams ] [ Unthrottled Broadcast ]
- Consumer calls `request(n)` - No feedback channel possible
- Producer pushes EXACTLY n items - Fast producer overwhelms consumer
- Example: Netflix DASH Video - Result: Packet drop or OOM
Backpressure Classification across Architectures:
- Requires Feedback Loop: Backpressure cannot exist without an active feedback loop between consumer and producer regulating generation rates.
- Reactive Streams (Dynamic Backpressure): Standardized via Java 9 Flow.Subscriber / request(n). The subscriber explicitly controls item delivery rates. Example: Netflix video player requesting chunk bitrates based on local buffer fill level and bandwidth.
- Broadcast / Sensor Telemetry (NO Backpressure): Live sports streams or IoT sensors cannot "pause time." Slow consumers must handle overload via dropping packets, downsampling, or crashing (OOM).
- Message Queues (Kafka / RabbitMQ): Message queues exist primarily for decoupling in space and time (acting as an asynchronous mediator). There is no direct backpressure feedback loop between producer and consumer; the broker buffers messages. If the broker fills up, it throttles the producer at the connection layer.
Q: Explain "Competing Consumers" pattern.
A: Attaching multiple consumer instances to a single message queue. The queue broker ensures each incoming message is delivered to only one consumer, enabling parallel processing and high-throughput execution.
Q: What is JTA (Java Transaction API)?
A: A standard Java EE/Jakarta specification that enables applications to manage distributed transactions across multiple XA-compliant resource managers (e.g., coordinating a transaction between a PostgreSQL DB and an IBM MQ broker).
Category 9: Testing & Quality (TDD/BDD)Q: Difference between Mock and Spy in Mockito.A:
- Mock: A dummy object created entirely from scratch. All methods return default null/0/false values unless explicitly stubbed (when()).
- Spy: Wraps an existing real instance. Executes real methods by default unless a specific method is explicitly stubbed.
Q: What is "Mutation Testing"?
A: A fault-based testing technique where a tool (like PITest) mutates source code operators (e.g., changing a + b to a - b, or flipping > to <). If your unit test suite continues to pass despite the code mutation, the test survived—indicating weak assertions or inadequate coverage.
Q: Explain @ParameterizedTest in JUnit 5.
A: Enables running a single test method repeatedly with different arguments (supplied via @ValueSource, @CsvSource, or @MethodSource).
Q: How do you test private methods?
A: You shouldn't test private methods directly. Test them through the public API methods that invoke them.
The Architectural Philosophy:
Private methods are implementation details, not API contracts. Tests must focus on behavior (what a class does), not implementation (how it does it).
- Test via Public API: If a private method contains logic, that logic is exercised by a public method. Writing comprehensive tests against all execution paths of the public API automatically tests the private method, achieving 100% test coverage without breaking encapsulation.
- Encapsulation Takes Priority: Bypassing private visibility via Reflection or changing methods to package-private purely for test access creates fragile tests bound to internal variable names. Refactoring private internals breaks tests even when external behavior remains 100% correct.
- When Private Methods Get Too Complex: If a private method becomes so complex that testing it through the public interface feels impossible, it indicates a violation of the Single Responsibility Principle (SRP). Refactor the complex logic into its own dedicated class as a public method, inject that new class into the primary service, and test the extracted class directly.
Category 10: Performance & Modern Java (Java 17 to 25 Focus)
Q: What is "Application Class Data Sharing" (AppCDS)?
A: Reduces JVM startup time and memory footprint by pre-parsing and dumping class metadata into an archived .jsa file during build time, which can be memory-mapped across multiple running JVM processes.
Q: Explain Sealed Classes (Java 17).
A: Restricts which classes or interfaces may extend or implement them using the permits keyword, providing compile-time control over inheritance hierarchies and facilitating exhaustive pattern matching.
public sealed interface Shape permits Circle, Rectangle {}
Q: What are "Records" in Java 14+?
A: Immutable nominal tuple data carriers. The compiler automatically generates final fields, canonical constructors, equals(), hashCode(), and toString() implementations.
Q: What is the SequencedCollection interface in Java 21?
A: A core collection interface introducing a unified API for accessing first and last elements, and retrieving reversed views across ordered collections (e.g., List, Deque, LinkedHashSet). Methods include getFirst(), getLast(), addFirst(), addLast(), and reversed().
Q: Explain ZGC (Z Garbage Collector).
A: A concurrent, low-latency garbage collector designed to handle heaps scaling from megabytes to 16 Terabytes with sub-millisecond pause times by using colored pointers and load barriers.
Category 11: Protocol Architecture Decision Matrix
Webhooks as the HTTP-based Observer Pattern:Webhooks are structurally an HTTP-based, cross-system implementation of the Observer Pattern:
- Subject: Webhook Publisher (e.g., Stripe, GitHub)
- Observer: Webhook Consumer (Your HTTP endpoint URL)
- Registration: Configuring your URL callback in developer settings
- Notification: HTTP POST request containing event JSON payloads
RSS Feed