Java / Pub-Sub Interview Questions 2026
82 Java / Pub-Sub interview questions from LTIMindtree, TCS, Amazon, Razorpay, LinkedIn, Oracle, Accenture, Swiggy, Meta, Microsoft, Flipkart, Salesforce, PayU, Deloitte and more. Real questions from Technical, System Design, and HR rounds.
All Java / Pub-Sub Questions
Explain service discovery in microservices. How does Eureka work with Spring Cloud?
Design a distributed session system for a multi-instance Spring Boot application. Users shouldn't lose sessions when server restarts.
What is Spring Boot Actuator? What security risks does it introduce and how do you mitigate them?
Explain how Spring Boot auto-configuration works. How does it know which beans to create?
Your Java microservice has slow startup times (20 seconds) because it initializes many Spring beans. How do you reduce startup time?
Explain Java's WeakReference, SoftReference, and PhantomReference. Give practical use cases.
What is the Java memory model and happens-before relationship? Why does it matter for concurrent code?
Explain how Java's CompletableFuture works. How do you chain async operations and handle errors?
What is the Fork/Join framework in Java? How does it differ from ExecutorService for CPU-bound tasks?
Explain what a deadlock is and how to prevent one in a multi-threaded Java application.
Explain the difference between synchronized, ReentrantLock, and ConcurrentHashMap for protecting shared state in Java. When would you choose each?
You have a Spring Boot service that reads from a config file. In production, changing the config requires a restart. Implement dynamic config refresh without restart.
In a Java 17 application, you see OutOfMemoryError: Metaspace. The heap is fine. What is Metaspace, what causes it to fill up, and how do you fix it?
What is the difference between ArrayList and LinkedList performance? When would you ever choose LinkedList?
You have a Java application with a class hierarchy 10 levels deep using inheritance. New requirements keep breaking existing behavior. A senior architect says 'prefer composition over inheritance'. Refactor this without changing the external API.
Explain Java's try-catch-finally execution order. What happens when both catch and finally throw exceptions?
Your application uses @Async in Spring Boot but tasks are dropping silently. No exceptions are logged. The async methods return void. How do you debug and fix this?
A developer uses List<Object> to store mixed types and casts on retrieval. What are the problems and how would you fix this with Java generics?
What is Java's sealed class hierarchy (Java 17+)? How does it improve pattern matching?
Explain the difference between synchronized, ReentrantLock, ReadWriteLock, and StampedLock. Give a scenario where each is the right choice.
Explain CompletableFuture in Java 8+. How do you run 3 API calls in parallel and combine results when all complete?
Explain Java records (Java 16+). What problems do they solve compared to regular classes?
Your Spring Boot microservice processes 10,000 HTTP requests per minute. You add a feature that makes one additional database call per request. Response time jumps from 50ms to 800ms. Explain the performance model and fix.
Your Java application uses Hibernate. You notice N+1 queries when loading a list of entities with a @OneToMany relationship. Fix this without changing the database schema.
What is Project Loom (virtual threads) in Java 21? How does it change the threading model?
Design a thread-safe cache in Java that: evicts the least recently used entry when full, has O(1) get and put, and handles concurrent access without a global lock.
You have a microservice with 50 REST endpoints built with Spring Boot. A new requirement says every request must log user ID, request ID, and duration. You cannot modify 50 controllers. How do you implement this?
You're seeing ConcurrentModificationException in production but not in tests. The code iterates over a HashMap inside a method that looks safe. What are the possible causes in a multi-threaded environment?
Explain why String is immutable in Java. What problem would occur if String were mutable? Give a concrete security example.
Explain how Java's Garbage Collector works in G1GC mode. Your application has 8GB heap and full GCs every 10 minutes cause 5-second pauses. How do you tune this?
You have a Java service that processes files. After processing 100 files, you get OutOfMemoryError: GC Overhead Limit Exceeded. Your code closes all streams. What else could cause this?
You're asked to estimate migrating a 10-year-old codebase from Java 8 to Java 17. Your manager wants the number by end of day. The codebase has 500,000 lines of code. What do you do?
Explain the difference between the young generation and old generation in JVM garbage collection. Why do most GC pauses come from minor (young-gen) collections rather than major ones, and when does that assumption break down?
Your Spring Boot application starts fine but after 2 hours of production traffic, all requests start returning HTTP 500 with 'Unable to acquire JDBC Connection'. Memory and CPU look normal. What's happening?
Explain the difference between checked and unchecked exceptions in Java. Why do some frameworks (Spring, Lombok) convert checked to unchecked?
You have a Spring Boot application where @Transactional is not working — changes are not being rolled back on exceptions. You've verified the exception is a RuntimeException. What are the possible causes?
What is the Java Memory Model (JMM)? Give a specific example where code behaves correctly in single-threaded but incorrectly in multi-threaded execution without synchronization.
Explain constructor injection vs field injection (@Autowired on a field) in Spring. Why do most teams now prefer constructor injection?
Your Spring Boot application beans form a circular dependency: A depends on B, B depends on A. It fails at startup. How do you resolve this without @Lazy?
Explain the difference between an abstract class and an interface in Java. With default methods now allowed in interfaces since Java 8, when would you still choose an abstract class?
Explain Java's Optional. A code review shows: Optional.get() called without isPresent() check. What's the problem and what's the idiomatic fix?
What is the difference between HashMap and ConcurrentHashMap at the implementation level? When does ConcurrentHashMap still cause problems?
Your Spring Boot startup time is 45 seconds with 200 beans. How do you reduce it?
Design a thread-safe singleton in Java. What are the pitfalls of double-checked locking?
What does @SpringBootApplication actually do? Which three annotations does it combine, and what does each one do?
Your Java application creates a new Thread inside a loop that processes 10,000 items. Each thread makes a database call. Why is this a bad design and how do you fix it?
Your microservice calls 5 external services. You want to test it in isolation without calling real services. How do you set up testing?
What is the difference between volatile and synchronized in Java? When is volatile sufficient?
What is a race condition in Java, and how does synchronized prevent it? Show a minimal example of a non-thread-safe counter and the fix.
You call a @Transactional service method from another @Transactional method in the same class. What transaction behavior do you get, and why?
Explain what happens when Spring beans have different scopes: @Singleton depends on @Prototype. What's the problem and how do you fix it?
You're implementing a REST API with Spring Boot. How do you handle validation and return proper error responses without try-catch in every controller?
What does Spring Boot Actuator give you out of the box for a microservice running in production? Name at least 3 endpoints and what each is used for.
Explain the difference between @Component, @Service, @Repository, and @Controller in Spring. Are they interchangeable?
You have a @RestController that takes a large request body (100MB file upload). Server runs out of heap memory when multiple uploads happen simultaneously. Fix this.
Explain how Java's try-with-resources works. What happens if both the try block and close() throw exceptions?
What is a memory leak in Java despite having a garbage collector? Give a concrete example involving a static collection.
Why must you override hashCode() whenever you override equals() in Java? What breaks if you only override equals()?
What is Spring's ApplicationContext vs BeanFactory? When would you use BeanFactory?
What is Java's ClassLoader hierarchy and when does it cause ClassCastException across classloaders?
Design a REST controller in Spring Boot for a "create order" endpoint. What annotations and validation would you use to ensure a malformed request returns 400 instead of crashing?
You need a collection that maintains insertion order AND gives O(1) lookup by key. Which Java collection would you use, and why not a plain HashMap?
Your REST API uses JWT. A user changes their password. How do you immediately invalidate their existing JWT tokens?
Your Java service has two threads simultaneously checking product stock (quantity=1). Both see available and create orders, resulting in quantity=-1. Fix this.
Rewrite this imperative loop using Java Streams: filter a list of orders for status "PAID", then sum their amounts. Explain one case where a stream would actually perform worse than the loop.
Write a Java application that publishes a message to Google Cloud Pub/Sub when a new payment is processed.
Explain Spring Security's filter chain. What's the order of filters and why does it matter?
Your Spring Boot app is hitting 429 rate limit errors from an external API. Implement a solution.
How do you implement centralized exception handling across all controllers in a Spring Boot application, so you don't repeat try/catch in every endpoint?
When would you use the Builder pattern in Java instead of a constructor with many parameters? Sketch a builder for a User class with 6 optional fields.
Your Spring Boot app has 20 @Scheduled tasks. In a multi-instance deployment, all 10 instances run every scheduled task simultaneously, causing duplicate processing. How do you fix this?
What are functional interfaces in Java 8? List the four main ones and their use cases.
What is the difference between a checked and an unchecked exception in Java? Why do many teams avoid checked exceptions for business logic errors?
Explain Spring Boot auto-configuration. How does @ConditionalOnClass work? Write a scenario where it prevents a bean from being created.
Write a Java 8 Stream pipeline: filter employees earning >50K, group by department, compute average salary per department, sorted by average descending.
Your Spring Boot service exposes 50 REST endpoints. How do you implement versioning so old clients using /v1 still work while new clients use /v2?
Your Java app's heap dump shows hundreds of thousands of HashMap$Entry objects. What are the likely causes?
Explain differences between abstract class and interface in Java 8+. With default methods in interfaces, when would you still choose abstract class?
Explain how Spring Boot handles connection pooling with HikariCP. What happens when the pool is exhausted?
What is Spring Batch? How does it handle restartable jobs that fail midway through processing 1 million records?
Your Spring Boot microservice calls another service via Feign client. The downstream service is slow (30 second response). How do you prevent your service from hanging?
What is Spring Security's filter chain? How would you implement JWT authentication in it?
Practice these questions with AI feedback
Get instant grading on your answers, identify your weak areas, and generate a personalised 14-day study plan — all free.
Build my study plan →