Java Scenario Questions

Question : What happens internally when you start a spring boot application?

Ans : When you start a Spring Boot application (typically by running the main method with SpringApplication.run(...)), a lot happens under the hood. Let me walk you through the step-by-step internal process:

1. Main method execution
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
The SpringApplication class is the entry point.
It prepares and launches the Spring context.

2. SpringApplication initialization
When you call new SpringApplication(...):
Determines the type of application (web / reactive / non-web) by checking classpath (DispatcherServlet, WebFlux, etc.).
Sets up defaults (e.g., banner, logging system, ApplicationContext class).
Loads ApplicationContextInitializer and ApplicationListener implementations via spring.factories.

3. Run method of SpringApplication
When run() is invoked:
1. Prepare Environment
Creates/loads a ConfigurableEnvironment (contains application.properties, system/env variables).
Determines active profiles.
Publishes ApplicationEnvironmentPreparedEvent.

2. Prepare ApplicationContext
Chooses the correct type:
AnnotationConfigServletWebServerApplicationContext (Spring MVC)
AnnotationConfigReactiveWebServerApplicationContext (WebFlux)
AnnotationConfigApplicationContext (non-web)
Loads ApplicationContextInitializers.

3. Create ApplicationContext
Instantiates the chosen context.
Applies initializers.
Publishes ApplicationContextInitializedEvent.

4. Bean definition loading
Uses @SpringBootApplication (meta-annotation for @Configuration, @EnableAutoConfiguration, @ComponentScan).
Performs component scanning → detects beans, services, repositories, controllers.
Loads auto-configuration classes from META-INF/spring.factories (based on classpath).
Creates bean definitions but does not instantiate yet.

5. Bean instantiation & dependency injection
The IoC container instantiates beans.
Applies dependency injection (@Autowired, constructor injection).
Applies AOP proxies, aspects, and BeanPostProcessors.
Publishes ApplicationPreparedEvent.

6. Web server startup (if web app)
If it's a web app, Boot starts an embedded server (Tomcat, Jetty, or Undertow).
Creates and configures DispatcherServlet.
Registers request mappings from @Controller and @RestController.

7. ApplicationRunner and CommandLineRunner
After the context is ready, any beans implementing these interfaces are executed.

8. ApplicationReadyEvent
The application is now fully started.
Listeners can perform post-startup logic.

The app is ready to accept requests. 



πŸ‘‰ “How would you efficiently read a large file into memory?”


This checks your ability to balance performance vs memory limits.


πŸ”Ή NaΓ―ve Approach – Load Entire File

// Loads everything into memory
List<String> lines = Files.readAllLines(Paths.get("bigfile.txt"));

❌ If the file is 2GB and your JVM heap is 512MB → OutOfMemoryError.
⚠️ Not scalable for large files.


πŸ”Ή Efficient Approach – Stream Processing

try (Stream<String> stream = Files.lines(Paths.get("bigfile.txt"))) {
stream.forEach(line -> {
// process line by line
});
}

✅ Reads lazily, keeps memory footprint small.
✅ Suitable for GB-scale log or CSV files.


πŸ”Ή Alternative – NIO with FileChannel

try (FileChannel channel = FileChannel.open(Paths.get("bigfile.txt"))) {
ByteBuffer buffer = ByteBuffer.allocate(1024); // 1KB chunks
while (channel.read(buffer) > 0) {
buffer.flip();
// process buffer content
buffer.clear();
}
}

✅ Chunk-based reading.
✅ Good for binary/structured files (images, large data exports).


πŸ”Ή Real-World Scenarios

Processing server logs (100MB–2GB daily).

Streaming financial transactions from CSVs.

Handling big JSON/XML files for ETL jobs.




1️⃣ “Your Spring Boot app suddenly throws OutOfMemoryError in production. What steps do you take to investigate?”
πŸ”Ž Looking for: Heap dump analysis, GC tuning, spotting memory leaks, profiling mindset.

2️⃣ “A request that normally takes 200ms now takes 20s under load. How do you approach performance tuning?”
πŸ”Ž Looking for: Profiling-first mindset, analyzing DB queries, optimizing thread pools, caching strategy.

3️⃣ “You inherit a legacy service with no tests. How do you add new features safely?”
πŸ”Ž Looking for: Test-first approach, refactoring strategy, incremental improvements.

4️⃣ “Your microservice is consuming a Kafka topic but lags behind by millions of messages. How do you diagnose?”
πŸ”Ž Looking for: Knowledge of consumer groups, partition rebalancing, offset management, backpressure handling.

5️⃣ “Users report random 500 errors from your API, but logs look fine. What’s your next step?”
πŸ”Ž Looking for: Ability to reproduce issues, distributed tracing, log correlation, observability skills.

6️⃣ “You deploy a service that works locally but fails in Kubernetes. How do you debug?”
πŸ”Ž Looking for: Containerization basics, config/environment issues, readiness/liveness probes, networking.

7️⃣ “A batch job that processes 1M records fails halfway with no clear error. How do you fix it?”
πŸ”Ž Looking for: Retry strategies, idempotency, chunking, monitoring.


Core Java & OOP
- What is the difference between final, finally, and finalize()?
- Can a static method be overridden? Why or why not?
- How does Java’s ClassLoader work?
- Explain Enum in Java — how is it different from constants defined in an interface?
- What is the difference between shallow copy and deep copy?

Collections & Generics
- What is the difference between Comparable and Comparator?
- What are fail-fast vs fail-safe iterators? Give examples.
- Can we store null keys and values in HashMap, ConcurrentHashMap, and TreeMap?
- What is a bounded wildcard (<? extends T> vs <? super T>) in generics?
- Why are hashCode() and equals() both needed in collections?

Concurrency
- Explain difference between synchronized block vs synchronized method.
- What is the difference between CyclicBarrier and CountDownLatch?
- How does AtomicInteger work internally?
- Explain the concept of thread starvation and deadlock. How to prevent them?
- What is the difference between Callable and Runnable?

Spring & Microservices
- What is the difference between @Bean and @Component in Spring?
- How does Spring Boot autoconfiguration (@EnableAutoConfiguration) actually work?
- What is @ControllerAdvice in Spring Boot?
- How would you secure a REST API in Spring Boot (JWT/OAuth2)?
- Explain circuit breaker pattern in microservices.

Database / Persistence
What are dirty checking and persistence context in Hibernate?
How do optimistic locking and pessimistic locking differ in JPA?
What is N+1 query problem in JPA and how do you solve it?
What is difference between EntityManager and Session in JPA/Hibernate?
Explain cascading types in JPA (PERSIST, MERGE, REMOVE, ALL).




πŸš€Java Performance Tuning – Scenario Based Interview Prep

In senior-level Java interviews, you’re often given real-world performance issues and asked how you’d approach them. It’s not just about theory – it’s about your debugging mindset.

Here are 4 common scenario-based questions with answer approaches πŸ‘‡


πŸ”Ή Scenario 1 – High GC & Latency

Problem: Spring Boot app slows down with frequent Full GC, high CPU, and latency spikes.
Approach: Check GC logs → Analyze heap → Tune JVM GC params → Optimize memory-heavy code → Validate with load testing.

πŸ”Ή Scenario 2 – Memory Leak

Problem: Service crashes after hours with OutOfMemoryError. Heap dump shows uncollected objects.
Approach: Capture heap dump → Identify leak suspects → Fix session handling / static refs → Release objects properly → Monitor memory usage post-fix.

πŸ”Ή Scenario 3 – Slow Database Queries

Problem: Queries take 5+ sec, threads waiting on DB connections, throughput low.
Approach: Enable SQL logging → Optimize queries & indexes → Tune connection pool → Add caching → Use batch operations.

πŸ”Ή Scenario 4 – Thread Deadlock

Problem: App hangs, thread dump shows BLOCKED threads, synchronized deadlocks.
Approach: Analyze thread dump → Reduce lock scope → Use Lock API with timeout → Adopt concurrent utilities → Test under load.



πŸ”Ή Core Java & Concurrency
1️⃣ 🏦 Two threads update a bank account balance → how do you ensure consistency?
2️⃣ πŸ”„ Two threads access a HashMap simultaneously → what happens & how do you fix it?
3️⃣ πŸ’₯ Service crashes with OutOfMemoryError in production → how will you debug?
4️⃣ πŸ“‚ You need to store millions of records & frequently search → choose HashMap, TreeMap, or ConcurrentHashMap? Why?
5️⃣ 🧩 How would you design a thread-safe Singleton class?

πŸ”Ή Exception Handling
6️⃣ ⚠️ A REST API sometimes returns null, sometimes throws exceptions → how do you handle both?
7️⃣ πŸ“’ A checked exception occurs deep in the code → how do you propagate without breaking contracts?
8️⃣ πŸ” A third-party service fails randomly → how would you handle retries & fallbacks?

πŸ”Ή SQL & Database
9️⃣ πŸš‰ Two users try to book the same train seat → how do you ensure only one booking succeeds?
πŸ”Ÿ 🐒 A table has millions of rows & queries are slow → how do you optimize performance?
1️⃣1️⃣ πŸ“œ How do you implement efficient pagination without OFFSET slowness?
1️⃣2️⃣ πŸ“ You need to audit all changes (insert/update/delete) → how would you design it?

πŸ”Ή Spring Boot
1️⃣3️⃣ πŸ”€ If you have two APIs with the same path & method, what will happen?
1️⃣4️⃣ ⏳ A JWT token expires while user is still active → how do you refresh it?
1️⃣5️⃣ πŸ“ You need to log only certain APIs → use a Filter or Interceptor? Why?
1️⃣6️⃣ πŸ”„ You face a circular dependency between beans → how do you resolve it?

πŸ”Ή Microservices
1️⃣7️⃣ πŸ›‘️ If one microservice goes down → how do you prevent cascading failures?
1️⃣8️⃣ πŸ’³ Payment service double-charges users under high load → how do you debug & fix it?
1️⃣9️⃣ πŸ”‘ How do you ensure idempotency in a payment API?
2️⃣0️⃣ πŸ”— You need a distributed transaction across Order, Payment, Inventory → how do you handle it?
2️⃣1️⃣ πŸ“Œ How do you manage API versioning without breaking clients?
2️⃣2️⃣ 🐒 One microservice is slow & degrading performance → how do you isolate & fix it?
2️⃣3️⃣ πŸ“ˆ During Black Friday traffic, how do you scale services to handle 1M+ requests/minute?



πŸ’‘ How Stripe Prevents Double Payments With Idempotent APIs
Imagine you click “Pay” on a checkout page. The network glitches. You click again. Suddenly, two payments are deducted. πŸ’Έ
Not a great customer experience, right?
To solve this, Stripe (and many other payment platforms) uses Idempotent APIs.

πŸ”‘ What does that mean?
An idempotent API ensures that even if you retry the same request multiple times, it will only be processed once.
Here’s how Stripe makes it work:

1️⃣ Idempotency Keys
Each request carries a unique key (UUID).
Server checks: “Have I seen this key before?”
If no → Process request, save the key + response.
If yes → Just return the cached response, no double processing.
2️⃣ Caching & Expiry
The response for that key is cached in an in-memory DB.
Keys auto-expire after 24 hours → keeping storage light but still safe for retries.
3️⃣ Retries Without Fear
Clients can safely retry failed requests.
But retries need to be smart to avoid overwhelming servers.

✅ Solution: Exponential Backoff with Jitter
Exponential Backoff → Increase wait time after each retry:
1st retry: wait 1s
2nd retry: wait 2s
3rd retry: wait 4s
4th retry: wait 8s …

Jitter → Add randomness to the wait:
Instead of always waiting exactly 2s, wait randomly between 1–3s.
This spreads retries across time, so all clients don’t hammer the server at once.
⚡ The result?
πŸ‘‰ No accidental double charges.
πŸ‘‰ Resilient APIs, even during network failures.
πŸ‘‰ A smoother, safer payment experience.
✨ Simplicity wins again: one small UUID + smart retries can save millions of dollars in avoided errors.



Possible Approaches: πŸ€”

1. Database row-level lockingπŸ”’: Lock the specific row in the database to prevent concurrent updates.
2. Optimistic locking with retries πŸ”„: Use optimistic locking to detect conflicts and retry the operation if necessary.
3. Distributed lock (e.g., Redis/Zookeeper) 🌐: Use a distributed lock to synchronize access to the shared resource.
4. Queue requests and process sequentiallyπŸ“: Queue incoming requests and process them one by one to ensure consistency.



⚡ Possible Approaches:

1. Database Row-Level Locking πŸ”

Lock the row during update (SELECT … FOR UPDATE).

Prevents race conditions, but can cause blocking under high load.

Works fine for small scale but doesn’t scale well in flash-sale scenarios.

2. Optimistic Locking with Retries πŸ”„

Each row has a version column.

When updating, you check the version. If someone else already updated, your update fails → you retry.

Prevents overbooking, avoids blocking, and scales well.

Best fit when conflicts are rare or manageable.

3. Distributed Lock (Redis/Zookeeper) 🌍

Use a distributed system to synchronize access to shared resources.

Ensures consistency across multiple application instances.

Adds external dependency and can become a bottleneck if not designed carefully.

4. Queue Requests & Process Sequentially ✉️

Put booking requests into a queue.

Process them one by one → natural ordering, no conflicts.

Guarantees consistency but increases latency.

πŸ’‘ My Choice → Optimistic Locking with Retries

Here’s why:

Prevents overbooking without blocking every request.

Ensures data consistency using a simple version check.

Scales better than row-level locks or distributed locks for high-traffic systems.

Example in Java (JPA/Hibernate):

@Entity
class EventInventory {
@Id Long eventId;
int available;
@Version long version;
}

When multiple users try to book:

The first update succeeds and increments the version.

The next update sees version mismatch → throws OptimisticLockException → retried.

This way, no two users can decrement the same ticket count simultaneously.

⚠️ Real-World Considerations:

For flash sales (thousands of requests/sec), add Redis Lua scripts or partitioned queues.

Always use idempotency keys to avoid duplicate reservations.

Add short-lived reservation holds (e.g., 2 minutes) → tickets are confirmed only after successful payment.
---

✅ Takeaway:
There’s no “one-size-fits-all” solution.

For smaller scale → Row Locking works.

For high concurrency → Optimistic Locking is efficient.

For extreme load (millions of users) → Redis + Queues + Event-driven design.





πŸ”Ή Core Java (Advanced)

1. Explain ThreadLocal — where exactly would you use it in real projects?

2. Can you design a custom immutable class in Java? What pitfalls should you avoid?

3. How does ConcurrentHashMap achieve thread safety? Explain segment locking.

4. What’s the difference between synchronized and ReentrantLock? Which one is better for high concurrency?

5. Explain the working of ForkJoinPool.

πŸ”Ή Spring / Spring Boot

6. How does Spring manage circular dependencies?

7. Difference between @Bean, @Component, @Service, @Repository. When do you prefer each?

8. How do you implement global exception handling in Spring Boot REST APIs?

9. How do you configure asynchronous execution in Spring Boot?

10. If your Spring Boot app is consuming high memory in production, how would you debug it?

πŸ”Ή Microservices & Design

11. How do you handle data consistency across microservices without distributed transactions?

12. Explain the Saga pattern with an example.

13. How do you secure microservices communication? (JWT, OAuth2, API Gateway)

14. What happens if Kafka consumer is slower than producer? How do you handle backpressure?

15. If two microservices are dependent and one goes down, how do you prevent a cascade failure?

πŸ”Ή SQL & Problem Solving

16. Write a query to find the second highest salary in a table without using TOP or LIMIT.

17. Difference between Index Scan vs Index Seek — which one is faster?

18. Explain ACID properties with real examples.

19. How do you debug deadlocks in DB queries?

20. Write a query to find duplicate emails in a user table.

πŸ”Ή Real-time Scenarios

21. Suppose your payment service is working fine in QA but failing randomly in Production — how would you debug?

22. You deployed a new version of a microservice and API response time doubled — what steps will you take?

23. How would you design a rate limiter for APIs in Spring Boot?

24. If multiple users try to update the same record at the same time, how would you handle it?

25. How do you debug a memory leak in a live application?




⚡ Scenario Questions

1️⃣ “Your Spring Boot app suddenly throws OutOfMemoryError in production. What steps do you take to investigate?”
πŸ”Ž Looking for: Heap dump analysis, GC tuning, spotting memory leaks, profiling mindset.

2️⃣ “A request that normally takes 200ms now takes 20s under load. How do you approach performance tuning?”
πŸ”Ž Looking for: Profiling-first mindset, analyzing DB queries, optimizing thread pools, caching strategy.

3️⃣ “You inherit a legacy service with no tests. How do you add new features safely?”
πŸ”Ž Looking for: Test-first approach, refactoring strategy, incremental improvements.

4️⃣ “Your microservice is consuming a Kafka topic but lags behind by millions of messages. How do you diagnose?”
πŸ”Ž Looking for: Knowledge of consumer groups, partition rebalancing, offset management, backpressure handling.

5️⃣ “Users report random 500 errors from your API, but logs look fine. What’s your next step?”
πŸ”Ž Looking for: Ability to reproduce issues, distributed tracing, log correlation, observability skills.

6️⃣ “You deploy a service that works locally but fails in Kubernetes. How do you debug?”
πŸ”Ž Looking for: Containerization basics, config/environment issues, readiness/liveness probes, networking.

7️⃣ “A batch job that processes 1M records fails halfway with no clear error. How do you fix it?”
πŸ”Ž Looking for: Retry strategies, idempotency, chunking, monitoring.

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence