JVM & Performance Tuning

***1. Explain JVM architecture in detail

JVM (Java Virtual Machine) is the runtime engine that executes Java bytecode.

It provides:

  • platform independence
  • memory management
  • garbage collection
  • security

JVM Architecture Overview

Class Loader

Runtime Data Areas

Execution Engine

Native Method Interface

Native Libraries

1. Class Loader Subsystem

Loads .class files into JVM memory.


Main Responsibilities

  • Loading classes
  • Linking classes
  • Initialization

Class Loading Phases

Loading

Bytecode loaded into memory.


Linking

Includes:

  • Verification
  • Preparation
  • Resolution

Initialization

Static variables initialized.


2. Runtime Data Areas

Memory regions used by JVM.


Heap Memory

Stores:

  • objects
  • instance variables

Shared among threads.


Stack Memory

Stores:

  • method calls
  • local variables

Each thread has separate stack.


Method Area

Stores:

  • class metadata
  • static variables
  • constant pool

PC Register

Stores current instruction address for each thread.


Native Method Stack

Used for native (non-Java) methods.


3. Execution Engine

Executes bytecode.


Components

ComponentPurpose
InterpreterExecutes bytecode line by line
JIT CompilerConverts bytecode to native code
Garbage CollectorRemoves unused objects

4. Native Method Interface (JNI)

Allows Java to interact with:

  • C
  • C++
  • OS libraries

5. Native Libraries

External libraries used by native methods.


Important Interview Point:

JVM is platform-dependent, but Java bytecode is platform-independent.


***2. What is class loading mechanism?

Class loading mechanism is the process of dynamically loading classes into JVM memory during runtime.


Who Performs It?

ClassLoader Subsystem

Steps in Class Loading

1. Loading

Class bytecode loaded into memory.


2. Linking

Includes:

  • Verification
  • Preparation
  • Resolution

Verification

Checks bytecode validity.


Preparation

Allocates memory for static variables.


Resolution

Symbolic references replaced with actual references.


3. Initialization

Static blocks and static variables initialized.


Types of Class Loaders

ClassLoaderPurpose
Bootstrap ClassLoaderLoads core Java classes
Extension ClassLoaderLoads extension libraries
Application ClassLoaderLoads application classes

Parent Delegation Model

Child class loader first delegates loading request to parent.


Advantages

  • Security
  • Avoids duplicate loading
  • Efficient memory usage

Important Interview Point:

A class is loaded only once in JVM.


***3. Explain different Garbage Collectors in Java

Java provides multiple Garbage Collectors optimized for different workloads.


1. Serial Garbage Collector

Uses:

Single Thread

for garbage collection.


Features

  • Simple
  • Small applications
  • Causes stop-the-world pause

JVM Option

-XX:+UseSerialGC

2. Parallel Garbage Collector

Uses multiple threads for GC.


Features

  • Better throughput
  • Suitable for multi-core systems

JVM Option

-XX:+UseParallelGC

3. CMS (Concurrent Mark Sweep)

Minimizes pause time.


Features

  • Concurrent execution
  • Low latency

Problem

Memory fragmentation.


Status

Deprecated in Java 9.


4. G1 Garbage Collector

Divides heap into regions.


Features

  • Predictable pause time
  • Efficient large heap management

JVM Option

-XX:+UseG1GC

5. ZGC (Z Garbage Collector)

Designed for:

Very low latency

Features

  • Millisecond pauses
  • Large heaps support

6. Shenandoah GC

Reduces pause times using concurrent compaction.


Difference Table

GCBest For
Serial GCSmall apps
Parallel GCThroughput
CMSLow latency
G1 GCLarge heaps
ZGCUltra-low pause
ShenandoahLow pause large apps

Important Interview Point:

G1 GC became default collector from Java 9 onwards.


***4. What is G1 Garbage Collector?

G1 (Garbage First) GC is a server-style garbage collector designed for:

  • low pause times
  • large heap applications

Introduced in:

Java 7

Internal Working

Instead of fixed generations:

Heap divided into regions

Region Types

  • Eden
  • Survivor
  • Old
  • Humongous

Why Called Garbage First?

G1 prioritizes regions with:

Most garbage

for cleanup.


Features

  • Predictable pause times
  • Parallel processing
  • Concurrent marking
  • Efficient heap utilization

Advantages

  • Better large heap performance
  • Reduced Full GC
  • Lower pause times

JVM Option

-XX:+UseG1GC

Important Interview Point:

G1 GC balances:

  • throughput
  • latency
  • memory efficiency

***5. What are JVM tuning parameters?

JVM tuning parameters are command-line options used to optimize JVM performance.


Common JVM Parameters

Heap Size

Initial Heap Size

-Xms512m

Maximum Heap Size

-Xmx2g

Stack Size

-Xss1m

Garbage Collector Selection

G1 GC

-XX:+UseG1GC

Parallel GC

-XX:+UseParallelGC

GC Logging

-Xlog:gc

Metaspace Size

-XX:MaxMetaspaceSize=256m

Common Tuning Goals

  • Reduce GC pauses
  • Increase throughput
  • Optimize memory usage
  • Improve startup performance

Important Interview Point:

JVM tuning is workload-dependent; there is no universal configuration.


***6. Explain memory leaks with real-world examples

A memory leak occurs when objects remain reachable and cannot be garbage collected.


Why It Happens

Garbage Collector removes only:

Unreachable objects

Real-World Examples

1. Static Collections

Example

static List<Object> cache =
new ArrayList<>();

Objects remain forever.


2. Unclosed Database Connections

Connections consume memory/resources.


3. Listener Leaks

Event listeners registered but never removed.


4. ThreadLocal Leaks

ThreadLocal values not cleared in thread pools.


5. Large Cache Without Eviction

Cache continuously grows.


Symptoms

  • High memory usage
  • Frequent Full GC
  • Slow performance
  • OutOfMemoryError

Prevention

  • Remove unused references
  • Close resources properly
  • Use weak references when needed

Important Interview Point:

Java has automatic garbage collection, but poor coding practices can still cause memory leaks.


**7. What are escape analysis and stack allocation?

Escape Analysis is a JVM optimization technique that determines whether an object escapes a method/thread.


Object Escape

Escapes Method

Object returned or shared outside method.


Does Not Escape

Object used only inside method.


Example

void test() {

Student s = new Student();
}

Object may not escape.


Stack Allocation

If object does not escape:

JVM may allocate it on stack

instead of heap.


Benefits

  • Faster allocation
  • Reduced GC pressure
  • Better performance

JVM Option

-XX:+DoEscapeAnalysis

Important Interview Point:

Escape analysis is handled automatically by modern JVMs.


**8. What is bytecode in Java?

Bytecode is intermediate platform-independent code generated by Java compiler.


Flow

.java → javac → .class → JVM

Features

  • Platform-independent
  • Executed by JVM
  • Optimized by JIT compiler

Example

javac Test.java

Generates:

Test.class

Why Bytecode Matters

Enables:

Write Once, Run Anywhere

Bytecode Execution

JVM converts bytecode into machine code.


Important Interview Point:

Bytecode is not machine code; JVM interprets or compiles it.


**9. What is Just-In-Time (JIT) optimization?

JIT (Just-In-Time) compiler improves JVM performance by converting bytecode into native machine code during runtime.


Without JIT

Interpreter executes bytecode line by line.

This is slower.


With JIT

Frequently used methods compiled into:

Native Machine Code

Working Process

Step 1

Interpreter identifies frequently executed code.


Step 2

JIT compiles hot code into machine code.


Step 3

Native code reused directly.


Advantages

  • Faster execution
  • Runtime optimization
  • Better application performance

Types of JIT Compilers

CompilerPurpose
C1 CompilerFast compilation
C2 CompilerAggressive optimization

Important Interview Point:

JIT compilation is one reason Java achieves near-native performance.


*10. What is AOT compilation?

AOT (Ahead-Of-Time) compilation converts bytecode into native machine code before application execution.


Difference from JIT

FeatureJITAOT
Compilation TimeRuntimeBefore runtime
Startup TimeSlowerFaster
Runtime OptimizationBetterLimited

Advantages of AOT

  • Faster startup
  • Lower memory usage
  • Better for microservices

Example Technologies

  • GraalVM Native Image
  • jaotc tool

Working Flow

Bytecode → Native Binary

Use Cases

  • Cloud-native apps
  • Serverless functions
  • Containers

Important Interview Point:

AOT improves startup speed, while JIT generally provides better long-running performance.

Advanced Concurrency

***11. What is Java Memory Model (JMM)?

Java Memory Model (JMM) defines how threads interact with memory in Java.

It specifies:

  • visibility rules
  • ordering guarantees
  • memory consistency behavior

for multithreaded programs.

Purpose of JMM

Without JMM:

  • threads may see stale data
  • instruction reordering may occur
  • inconsistent results may happen

Main Components

1. Main Memory

Shared memory storing:

  • objects
  • instance variables
  • static variables

2. Thread Local Memory

Each thread has its own working memory/cache.

Threads copy variables from main memory into local memory.


Working Flow

Main Memory

Thread Local Cache

Thread Execution

Important Concepts

ConceptMeaning
VisibilityChanges visible across threads
AtomicityOperation completes fully
OrderingExecution sequence consistency

JMM Solutions

  • synchronized
  • volatile
  • locks
  • atomic classes

Example Problem

boolean flag = false;

One thread updates value, another may not immediately see update without synchronization.


Important Interview Point:

JMM mainly solves:

Concurrency visibility and ordering problems

***12. What is happens-before relationship?

Happens-before is a rule defined by JMM that guarantees:

Memory visibility and execution ordering

between operations.


Meaning

If operation A happens-before operation B:

  • changes made by A are visible to B
  • execution order guaranteed

Important Happens-Before Rules

1. Program Order Rule

Statements execute in order within thread.


2. Monitor Lock Rule

Unlock happens-before subsequent lock.


3. Volatile Variable Rule

Write to volatile variable happens-before read.


Example

volatile boolean flag = true;

Thread reading flag sees latest value.


4. Thread Start Rule

Calling:

start()

happens-before thread execution.


5. Thread Join Rule

Thread completion happens-before:

join()

returns.


Why Important?

Ensures:

  • thread safety
  • predictable execution

Important Interview Point:

Happens-before guarantees visibility, not just execution order.


***13. Difference between synchronized and Lock interface

Both provide thread synchronization, but Lock offers more advanced features.


synchronized

Built-in Java keyword.


Example

synchronized void display() {
}

Features

  • Automatic lock management
  • Simpler syntax

Lock Interface

Defined in:

java.util.concurrent.locks

Example

Lock lock = new ReentrantLock();

lock.lock();

try {
}
finally {
lock.unlock();
}

Difference Table

FeaturesynchronizedLock
TypeKeywordInterface
Lock ReleaseAutomaticManual
tryLock() SupportNoYes
FairnessNoYes
Interruptible LockNoYes

Advantages of Lock

  • Better flexibility
  • Timeout support
  • Multiple condition variables

Important Interview Point:

Always release Lock inside:

finally

block.


***14. Explain ConcurrentHashMap internals

ConcurrentHashMap is a thread-safe implementation of Map designed for high concurrency.


Key Features

  • Thread-safe
  • High performance
  • Concurrent read/write access

Java 7 Internal Working

Used:

Segment-based locking

Multiple segments allowed parallel access.


Java 8 Internal Working

Uses:

  • CAS operations
  • synchronized blocks at bucket level
  • Red-Black Trees for collisions

Structure

Bucket Array

Node / TreeNode

Collision Handling

  • Linked List
  • Converted to Red-Black Tree after threshold

Why Faster Than Hashtable?

Locks only specific bucket instead of entire map.


Important Methods

MethodPurpose
put()Insert value
get()Retrieve value
computeIfAbsent()Atomic insertion

Important Interview Point:

ConcurrentHashMap does NOT allow:

  • null keys
  • null values

***15. What is Compare-And-Swap (CAS)?

CAS is a low-level atomic operation used in concurrent programming.


Purpose

Update variable safely without locks.


Working Logic

If current value == expected value
update value
Else
retry

Example

AtomicInteger count =
new AtomicInteger(0);

count.compareAndSet(0, 1);

Advantages

  • Lock-free synchronization
  • Better performance
  • Reduced thread blocking

Used In

  • Atomic classes
  • ConcurrentHashMap
  • JVM internals

Problem

May suffer from:

ABA Problem

Important Interview Point:

CAS is implemented using CPU-level atomic instructions.


***16. What are atomic classes in Java?

Atomic classes provide lock-free thread-safe operations on variables.

Defined in:

java.util.concurrent.atomic

Common Atomic Classes

ClassPurpose
AtomicIntegerAtomic int operations
AtomicLongAtomic long operations
AtomicBooleanAtomic boolean operations
AtomicReferenceAtomic object references

Example

AtomicInteger count =
new AtomicInteger(0);

count.incrementAndGet();

Features

  • Thread-safe
  • Lock-free
  • High performance

Internal Working

Uses:

CAS operations

Advantages Over synchronized

  • Faster
  • Non-blocking
  • Better scalability

Important Interview Point:

Atomic classes provide atomicity but not complex synchronization logic.


***17. Explain ForkJoinPool framework

ForkJoinPool is a framework for parallel task execution.

Introduced in:

Java 7

Purpose

Efficiently process:

Recursive divide-and-conquer tasks

Working Principle

Fork

Task split into smaller subtasks.


Join

Results combined.


Example Flow

Large Task

Subtasks

Parallel Execution

Merge Results

Core Classes

ClassPurpose
ForkJoinPoolThread pool
RecursiveTaskReturns result
RecursiveActionNo result

Work-Stealing Algorithm

Idle threads steal tasks from busy threads.


Advantages

  • Better CPU utilization
  • Parallel execution
  • Efficient recursive processing

Important Interview Point:

Parallel streams internally use:

ForkJoinPool

**18. What is CompletableFuture?

CompletableFuture is an advanced asynchronous programming feature introduced in Java 8.


Purpose

  • Asynchronous task execution
  • Non-blocking programming
  • Chaining dependent tasks

Example

CompletableFuture.supplyAsync(() -> {

return "Hello";
});

Features

  • Async execution
  • Callback chaining
  • Exception handling
  • Task combination

Common Methods

MethodPurpose
supplyAsync()Async task with result
runAsync()Async task without result
thenApply()Transform result
thenAccept()Consume result

Example Chaining

CompletableFuture.supplyAsync(() -> 10)
.thenApply(x -> x * 2);

Advantages

  • Cleaner async code
  • Better scalability
  • Avoids callback hell

Important Interview Point:

CompletableFuture combines features of:

  • Future
  • Callback
  • Promise-style programming

**19. What is starvation and livelock?

Both are concurrency problems in multithreading.


Starvation

A thread never gets CPU/resources because other threads continuously dominate.


Example

Low-priority thread never executes.


Causes

  • Thread priority misuse
  • Unfair locks

Prevention

  • Fair scheduling
  • Balanced resource allocation

Livelock

Threads remain active but continuously respond to each other without making progress.


Example

Two people repeatedly moving aside for each other in hallway.


Difference Table

FeatureStarvationLivelock
Thread StateWaiting indefinitelyContinuously active
ProgressNoNo
CPU UsageLowHigh

Important Interview Point:

Deadlock → blocked forever
Livelock → active forever without progress

**20. Explain ReadWriteLock

ReadWriteLock allows:

  • multiple readers simultaneously
  • only one writer exclusively

Defined in:

java.util.concurrent.locks

Purpose

Improve performance in read-heavy applications.


Components

LockPurpose
Read LockMultiple readers allowed
Write LockExclusive access

Example

ReadWriteLock lock =
new ReentrantReadWriteLock();

Acquiring Read Lock

lock.readLock().lock();

Acquiring Write Lock

lock.writeLock().lock();

Advantages

  • Better concurrency
  • Improved performance
  • Efficient read operations

Use Cases

  • Caching systems
  • Shared configuration
  • Read-heavy databases

Important Interview Point:

Multiple readers can coexist, but writers require exclusive access.


*21. What is Phaser in Java concurrency?

Phaser is a synchronization barrier introduced in Java 7.

Defined in:

java.util.concurrent

Purpose

Coordinate multiple threads executing in phases.


Features

  • Dynamic thread registration
  • Multi-phase synchronization
  • Flexible barrier mechanism

Example

Phaser phaser = new Phaser(3);

Important Methods

MethodPurpose
register()Add participant
arrive()Signal phase completion
arriveAndAwaitAdvance()Wait for others

Working Example

Phase 1 Complete

All Threads Synchronize

Phase 2 Starts

Advantages Over CyclicBarrier

  • Dynamic participants
  • Multiple phases support
  • More flexible

Important Interview Point:

Phaser is useful in complex parallel workflows requiring staged execution.

Design Patterns & Architecture

***22. Explain SOLID principles

SOLID is a set of five object-oriented design principles used to create:

  • maintainable code
  • scalable applications
  • loosely coupled systems

Introduced by:
Robert C. Martin

SOLID Principles

LetterPrinciple
SSingle Responsibility Principle
OOpen/Closed Principle
LLiskov Substitution Principle
IInterface Segregation Principle
DDependency Inversion Principle

1. Single Responsibility Principle (SRP)

A class should have:

Only one reason to change

Bad Example

class Employee {

void calculateSalary() {
}

void saveToDatabase() {
}
}

Class has multiple responsibilities.


2. Open/Closed Principle (OCP)

Software entities should be:

Open for extension,
Closed for modification

3. Liskov Substitution Principle (LSP)

Child classes should replace parent classes without breaking behavior.


4. Interface Segregation Principle (ISP)

Clients should not depend on unused methods.

Prefer:

Small focused interfaces

5. Dependency Inversion Principle (DIP)

Depend on:

Abstractions, not concrete classes

Advantages of SOLID

  • Better maintainability
  • Easier testing
  • Reduced coupling
  • Improved scalability

Important Interview Point:

SOLID principles form the foundation of modern enterprise application design.


***23. Explain Microservices architecture

Microservices architecture is a design approach where an application is divided into:

Small independent services

Each service handles a specific business capability.


Example

E-commerce application may have:

  • User Service
  • Payment Service
  • Order Service
  • Inventory Service

Features

  • Independent deployment
  • Decentralized database
  • API communication
  • Scalability

Architecture Flow

Client

API Gateway

Microservices

Databases

Communication Methods

  • REST APIs
  • gRPC
  • Messaging queues

Advantages

  • Independent scaling
  • Faster deployment
  • Better fault isolation
  • Technology flexibility

Challenges

  • Distributed system complexity
  • Network latency
  • Data consistency
  • Monitoring difficulties

Important Interview Point:

Microservices are best suited for:

  • large-scale systems
  • cloud-native applications
  • independently deployable modules

***24. Difference between Monolithic and Microservices architecture

Both are software architecture styles but differ in deployment and scalability.


Monolithic Architecture

Entire application deployed as:

Single unit

Features

  • Simple development
  • Single codebase
  • Shared database

Microservices Architecture

Application divided into:

Independent services

Difference Table

FeatureMonolithicMicroservices
DeploymentSingle deploymentIndependent deployment
ScalabilityEntire app scaledIndividual service scaled
CodebaseSingleMultiple services
Fault IsolationWeakStrong
Development SpeedFaster initiallyBetter for large systems

Example

Monolithic

One WAR/JAR file contains:

  • authentication
  • payments
  • orders

Microservices

Separate deployable services for each module.


Important Interview Point:

Most startups begin with monolithic architecture and later migrate to microservices as complexity grows.


***25. What are design patterns categories?

Design patterns are reusable solutions to recurring software design problems.

They are mainly divided into:

Three categories

1. Creational Patterns

Deal with:

Object creation

Examples

  • Singleton
  • Factory
  • Builder
  • Prototype

2. Structural Patterns

Deal with:

Object composition

Examples

  • Adapter
  • Decorator
  • Facade
  • Proxy

3. Behavioral Patterns

Deal with:

Object interaction and communication

Examples

  • Observer
  • Strategy
  • Command
  • State

Summary Table

CategoryPurpose
CreationalObject creation
StructuralStructure/composition
BehavioralCommunication/behavior

Important Interview Point:

Design patterns are language-independent design solutions, not frameworks.


***26. Explain Factory, Singleton, Builder, and Strategy patterns

1. Factory Pattern

Creates objects without exposing creation logic.


Example

Vehicle v =
VehicleFactory.getVehicle("car");

Purpose

  • Loose coupling
  • Centralized object creation

2. Singleton Pattern

Ensures:

Only one object exists

Example

Singleton.getInstance();

Use Cases

  • Logger
  • Configuration manager

3. Builder Pattern

Constructs complex objects step-by-step.


Example

Student s = new Student.Builder()
.setId(1)
.build();

Advantages

  • Readable object creation
  • Flexible construction

4. Strategy Pattern

Encapsulates multiple algorithms and allows runtime selection.


Example

PaymentStrategy strategy;

Real-Life Example

Payment methods:

  • Credit Card
  • UPI
  • PayPal

Advantages

  • Runtime flexibility
  • Loose coupling

Important Interview Point:

Strategy Pattern follows:

Favor composition over inheritance

***27. Explain Dependency Injection and IoC

Dependency Injection (DI)

Dependency Injection is a technique where dependencies are provided externally instead of being created internally.


Without DI

class Car {

Engine engine = new Engine();
}

Tight coupling exists.


With DI

class Car {

private Engine engine;

Car(Engine engine) {
this.engine = engine;
}
}

Inversion of Control (IoC)

IoC means:

Control transferred from application to framework/container

Example

Framework manages:

  • object creation
  • lifecycle
  • dependency management

Types of Dependency Injection

TypeDescription
Constructor InjectionVia constructor
Setter InjectionVia setter
Field InjectionDirect field injection

Advantages

  • Loose coupling
  • Better testing
  • Easier maintenance

Framework Example

Spring Framework heavily uses IoC and DI.


Important Interview Point:

IoC is a principle, while DI is one implementation technique of IoC.


**28. What is CQRS?

CQRS stands for:

Command Query Responsibility Segregation

Main Idea

Separate:

  • read operations
  • write operations

into different models.


Components

ComponentPurpose
CommandModify data
QueryRead data

Traditional Model

Single model handles:

  • insert
  • update
  • select

CQRS Model

Separate models for:

  • writes
  • reads

Advantages

  • Better scalability
  • Optimized reads/writes
  • Cleaner architecture

Use Cases

  • Banking systems
  • E-commerce
  • Event-driven systems

Challenges

  • Increased complexity
  • Data synchronization issues

Important Interview Point:

CQRS is often combined with:

Event Sourcing

**29. What is Event-Driven Architecture?

Event-Driven Architecture (EDA) is a system design where components communicate through:

Events

What is an Event?

An event represents:

Something that happened

Example:

  • Order Placed
  • Payment Completed
  • User Registered

Architecture Flow

Producer → Event Broker → Consumer

Components

ComponentRole
ProducerGenerates event
BrokerTransfers event
ConsumerProcesses event

Popular Technologies

  • Apache Kafka
  • RabbitMQ
  • AWS SQS

Advantages

  • Loose coupling
  • High scalability
  • Asynchronous processing

Challenges

  • Debugging complexity
  • Event ordering
  • Event consistency

Important Interview Point:

Microservices architectures frequently use Event-Driven Architecture for asynchronous communication.


*30. Explain Circuit Breaker pattern

Circuit Breaker Pattern prevents repeated calls to failing services.

It improves:

  • fault tolerance
  • system stability
  • resilience

Real-Life Analogy

Electrical circuit breaker stops current flow during overload.


Problem Solved

Without circuit breaker:

  • failing service continuously receives requests
  • system resources get exhausted

States of Circuit Breaker

StateMeaning
ClosedNormal operation
OpenRequests blocked
Half-OpenTesting recovery

Working Flow

Failure Threshold Reached

Circuit Opens

Requests Blocked

Recovery Attempt

Advantages

  • Prevents cascading failures
  • Faster failure response
  • Improves system resilience

Popular Libraries

  • Resilience4j
  • Hystrix (deprecated)

Common Use Cases

  • Microservices communication
  • External API calls
  • Database failures

Important Interview Point:

Circuit Breaker is a critical resiliency pattern in distributed systems and microservices architectures.

Spring & Hibernate (Frequently Asked)

***31. What is Spring Framework?

Spring Framework is a powerful Java framework used for building:

  • enterprise applications
  • web applications
  • microservices

It provides:

  • dependency injection
  • aspect-oriented programming
  • transaction management
  • integration support

Main Goals of Spring

  • Reduce boilerplate code
  • Promote loose coupling
  • Simplify enterprise development

Core Features

FeaturePurpose
IoC ContainerManages objects/beans
Dependency InjectionLoose coupling
AOPCross-cutting concerns
Spring MVCWeb development
Transaction ManagementDatabase transaction handling

Example

@Component
class Engine {
}

Spring automatically manages object lifecycle.


Advantages

  • Modular architecture
  • Easy testing
  • Integration support
  • Lightweight framework

Important Interview Point:

Spring Framework is based heavily on:

IoC and Dependency Injection

***32. What is Spring Boot?

Spring Boot is an extension of Spring Framework used to simplify Spring application development.


Main Purpose

Reduce configuration complexity in Spring applications.


Key Features

  • Auto-configuration
  • Embedded servers
  • Starter dependencies
  • Production-ready features

Example

@SpringBootApplication
public class App {
}

Embedded Servers

Spring Boot provides built-in:

  • Tomcat
  • Jetty
  • Undertow

Advantages

  • Faster development
  • Minimal XML configuration
  • Easy deployment
  • Simplified setup

Important Interview Point:

Spring Boot follows:

Convention over Configuration

***33. Difference between Spring and Spring Boot

Both are related, but Spring Boot simplifies Spring development.


Difference Table

FeatureSpring FrameworkSpring Boot
ConfigurationManualAuto-configuration
Server SetupExternal server neededEmbedded server
Development SpeedSlowerFaster
Boilerplate CodeMoreLess
DeploymentWARExecutable JAR

Spring Framework

Requires:

  • XML configuration
  • manual dependency setup

Spring Boot

Provides:

  • starter dependencies
  • embedded server
  • auto configuration

Example

spring-boot-starter-web

automatically configures web application dependencies.


Important Interview Point:

Spring Boot is built on top of Spring Framework.


***34. What is dependency injection in Spring?

Dependency Injection (DI) is a mechanism where Spring provides required objects automatically instead of creating them manually.


Example Without DI

class Car {

Engine engine = new Engine();
}

Tight coupling exists.


With Spring DI

@Component
class Engine {
}

@Component
class Car {

@Autowired
Engine engine;
}

Spring injects dependency automatically.


Types of Injection

TypeDescription
Constructor InjectionThrough constructor
Setter InjectionThrough setter
Field InjectionDirect field injection

Advantages

  • Loose coupling
  • Better testing
  • Easier maintenance

Important Interview Point:

Constructor Injection is preferred in modern Spring applications.


***35. Bean scopes in Spring

Bean scope defines:

Lifecycle and visibility of Spring beans

Common Bean Scopes

ScopeDescription
singletonSingle object per container
prototypeNew object every request
requestOne bean per HTTP request
sessionOne bean per HTTP session

Default Scope

singleton

Example

@Scope("prototype")
@Component
class Student {
}

Singleton Scope

One shared object throughout application.


Prototype Scope

New object created every time bean requested.


Important Interview Point:

Spring beans are singleton by default.


***36. Constructor Injection vs Setter Injection

Both are dependency injection techniques in Spring.


Constructor Injection

Dependencies injected through constructor.


Example

class Car {

private Engine engine;

Car(Engine engine) {
this.engine = engine;
}
}

Advantages

  • Mandatory dependencies enforced
  • Better immutability
  • Easier testing

Setter Injection

Dependencies injected using setter methods.


Example

class Car {

private Engine engine;

void setEngine(Engine engine) {
this.engine = engine;
}
}

Advantages

  • Optional dependencies possible
  • Flexible configuration

Difference Table

FeatureConstructor InjectionSetter Injection
Dependency TypeMandatoryOptional
ImmutabilityBetterPoor
TestingEasierModerate

Important Interview Point:

Constructor Injection is generally recommended over Setter Injection.


***37. What is Spring AOP?

Spring AOP stands for:

Aspect-Oriented Programming

It is used to separate:

Cross-cutting concerns

from business logic.


Examples of Cross-Cutting Concerns

  • Logging
  • Security
  • Transactions
  • Monitoring

Main Components

ComponentPurpose
AspectCross-cutting logic
AdviceAction performed
Join PointExecution point
PointcutMatching condition

Example

@Aspect
class LoggingAspect {
}

Advantages

  • Cleaner code
  • Reusable logic
  • Better modularity

Important Interview Point:

Spring AOP mainly uses:

Proxy-based implementation

***38. What is Hibernate ORM?

Hibernate ORM is an Object Relational Mapping (ORM) framework used to simplify database operations in Java.


Purpose

Maps:

Java objects ↔ Database tables

Example

@Entity
class Student {
}

Features

  • Automatic SQL generation
  • Database independence
  • Caching support
  • Lazy loading

Advantages

  • Reduces JDBC boilerplate code
  • Simplifies CRUD operations
  • Supports object-oriented programming

Important Interview Point:

Hibernate internally uses JDBC for database communication.


***39. Difference between Hibernate and JDBC

Both are used for database operations, but abstraction level differs.


Difference Table

FeatureJDBCHibernate
LevelLow-level APIORM Framework
SQL WritingManualAutomatic
Boilerplate CodeMoreLess
CachingNo built-inYes
Object MappingManualAutomatic

JDBC

Developer manually handles:

  • SQL queries
  • ResultSet mapping
  • connection management

Hibernate

Automatically handles:

  • object mapping
  • SQL generation
  • caching

Important Interview Point:

Hibernate improves productivity but JDBC may provide finer control and better performance for simple operations.


***40. What is Lazy Loading in Hibernate?

Lazy Loading means:

Data is loaded only when needed

instead of loading immediately.


Example

Suppose:

Student → Courses

Courses loaded only when accessed.


Example

@OneToMany(fetch = FetchType.LAZY)

Benefits

  • Improves performance
  • Reduces memory usage
  • Avoids unnecessary database queries

Problem

May cause:

LazyInitializationException

if session closes before access.


Opposite

Eager Loading

loads data immediately.


Important Interview Point:

Lazy loading is default for:

collections in Hibernate

**41. What is JPA?

JPA stands for:

Java Persistence API

It is a specification for ORM in Java.


Important Clarification

JPA is:

Not an implementation

Popular JPA Implementations

  • Hibernate
  • EclipseLink

Purpose

Standardize:

  • object-relational mapping
  • persistence operations

Example

@Entity
class Employee {
}

Advantages

  • Standard API
  • Vendor independence
  • Easier database operations

Important Interview Point:

Hibernate is an implementation of JPA.


**42. Difference between @Component, @Service, @Repository, and @Controller

All are Spring stereotype annotations used for automatic bean detection.


@Component

Generic Spring-managed bean.


Example

@Component
class Utility {
}

@Service

Represents:

Business logic layer

Example

@Service
class UserService {
}

@Repository

Represents:

Data access layer

Features

Provides database exception translation.


@Controller

Handles:

Web requests

in Spring MVC.


Difference Table

AnnotationLayer
@ComponentGeneric
@ServiceBusiness layer
@RepositoryPersistence layer
@ControllerPresentation layer

Important Interview Point:

All these annotations are specialized forms of:

@Component

**43. What is Spring Security?

Spring Security is a powerful authentication and authorization framework for Spring applications.


Main Features

  • Authentication
  • Authorization
  • CSRF protection
  • Session management

Authentication

Verifies:

Who user is

Authorization

Determines:

What user can access

Example

@EnableWebSecurity

Common Security Features

  • JWT authentication
  • OAuth2
  • Password encoding
  • Role-based access

Important Interview Point:

Spring Security is highly customizable and widely used in enterprise applications.


*44. What are REST APIs?

REST stands for:

Representational State Transfer

REST APIs are web services that allow communication between systems using HTTP protocol.


HTTP Methods

MethodPurpose
GETRetrieve data
POSTCreate data
PUTUpdate data
DELETERemove data

REST API Example

GET /users/1

returns user information.


Features of REST

  • Stateless
  • Client-server architecture
  • Resource-based URLs
  • Uses JSON/XML

Example Spring Boot REST API

@RestController
class UserController {

@GetMapping("/users")
public List<User> getUsers() {
return users;
}
}

Advantages

  • Lightweight
  • Scalable
  • Platform independent

Important Interview Point:

REST APIs are stateless, meaning server does not store client session information between requests.

Advanced Java Concepts

***45. Reflection API in Java

Reflection API allows Java programs to inspect and manipulate:

  • classes
  • methods
  • fields
  • constructors

during runtime.

Defined in:

java.lang.reflect

Purpose

Reflection enables:

  • dynamic class loading
  • runtime inspection
  • framework development

Example

Class<?> cls = Class.forName("Student");

Accessing Methods

Method[] methods =
cls.getDeclaredMethods();

Accessing Fields

Field[] fields =
cls.getDeclaredFields();

Common Use Cases

  • Spring Framework
  • Hibernate ORM
  • Dependency Injection
  • Testing frameworks

Advantages

  • Dynamic behavior
  • Runtime flexibility
  • Useful for frameworks

Disadvantages

  • Slower performance
  • Breaks encapsulation
  • Security concerns

Important Interview Point:

Reflection is heavily used internally by:

  • Spring
  • Hibernate
  • JUnit

***46. What are annotations in Java?

Annotations provide metadata information about code.

Introduced in:

Java 5

Purpose

Used by:

  • compiler
  • JVM
  • frameworks

to process additional information.


Example

@Override
void display() {
}

Common Built-in Annotations

AnnotationPurpose
@OverrideMethod overriding
@DeprecatedMarks obsolete code
@SuppressWarningsSuppress compiler warnings

Custom Annotation Example

@interface MyAnnotation {
}

Meta-Annotations

AnnotationPurpose
@TargetWhere annotation applies
@RetentionAnnotation lifetime

Retention Policies

PolicyAvailability
SOURCECompiler only
CLASSStored in bytecode
RUNTIMEAvailable during runtime

Important Interview Point:

Frameworks like:

  • Spring
  • Hibernate
  • JUnit

heavily rely on annotations.


***47. What is dependency inversion principle?

Dependency Inversion Principle (DIP) is one of the:

SOLID principles

Principle Statement

High-level modules should not depend on low-level modules.
Both should depend on abstractions.

Bad Example

class Car {

Engine engine = new Engine();
}

High-level class directly depends on concrete class.


Better Example

interface Engine {
}

class PetrolEngine
implements Engine {
}

class Car {

Engine engine;

Car(Engine engine) {
this.engine = engine;
}
}

Benefits

  • Loose coupling
  • Better testability
  • Easier maintenance

Real-World Usage

Dependency Injection frameworks implement DIP.

Example:
Spring Framework


Important Interview Point:

DIP encourages:

Programming to interfaces, not implementations

***48. What is functional programming in Java?

Functional programming is a programming style focused on:

  • functions
  • immutability
  • declarative code

Introduced strongly in:

Java 8

Main Features

  • Lambda expressions
  • Functional interfaces
  • Stream API
  • Method references

Example

list.stream()
.filter(x -> x > 10)
.forEach(System.out::println);

Functional Concepts

ConceptMeaning
ImmutabilityData does not change
Pure FunctionsNo side effects
Higher-Order FunctionsFunctions as arguments

Advantages

  • Cleaner code
  • Easier parallel processing
  • Better readability

Important Interview Point:

Java supports:

Functional-style programming

but is not a pure functional language.


***49. Explain Stream pipeline

A Stream pipeline is a sequence of operations performed on Java streams.


Pipeline Structure

Source

Intermediate Operations

Terminal Operation

Example

list.stream()
.filter(x -> x > 5)
.map(x -> x * 2)
.forEach(System.out::println);

Components

1. Source

Creates stream.

Example:

list.stream()

2. Intermediate Operations

Transform stream.

Examples:

  • filter()
  • map()
  • sorted()

3. Terminal Operation

Produces final result.

Examples:

  • collect()
  • count()
  • forEach()

Important Features

  • Lazy evaluation
  • Internal iteration
  • Pipeline optimization

Important Interview Point:

Intermediate operations do not execute until terminal operation is called.


***50. What are spliterators?

Spliterator is an advanced iterator introduced in Java 8 for:

  • parallel traversal
  • efficient stream processing

Defined in:

java.util

Purpose

Split data into smaller parts for parallel processing.


Example

Spliterator<Integer> sp =
list.spliterator();

Important Methods

MethodPurpose
tryAdvance()Process one element
forEachRemaining()Process remaining
trySplit()Split into parts

Why Important?

Used internally by:

Stream API

for parallel streams.


Advantages

  • Better parallelism
  • Efficient traversal
  • Bulk data processing

Important Interview Point:

Spliterator supports both:

  • sequential
  • parallel iteration

**51. What is metaspace?

Metaspace is a JVM memory area introduced in:

Java 8

It replaced:

PermGen (Permanent Generation)

Purpose

Stores:

  • class metadata
  • method metadata
  • runtime constant pool

Key Difference from PermGen

FeaturePermGenMetaspace
Memory TypeJVM HeapNative Memory
ResizingFixedDynamic

Advantages

  • Reduced OutOfMemoryError
  • Dynamic memory allocation
  • Better class metadata handling

JVM Parameter

-XX:MaxMetaspaceSize

Important Interview Point:

Metaspace uses native memory, not heap memory.


**52. What is Unsafe class?

Unsafe is a low-level internal JVM class providing:

  • direct memory access
  • thread operations
  • CAS operations

Defined in:

sun.misc.Unsafe

Features

  • Allocate memory manually
  • Perform atomic operations
  • Bypass JVM safety checks

Example Uses

  • ConcurrentHashMap
  • Atomic classes
  • High-performance frameworks

Why Dangerous?

It can:

  • crash JVM
  • corrupt memory
  • bypass security

Example

Unsafe unsafe;

Modern Alternatives

  • VarHandle
  • Foreign Memory API

Important Interview Point:

Unsafe is mainly intended for JVM/internal library development.


**53. What is dynamic proxy?

Dynamic Proxy allows creation of proxy objects during runtime.


Purpose

Intercept method calls dynamically.


Common Use Cases

  • Spring AOP
  • Transaction management
  • Logging
  • Security

Example

Proxy.newProxyInstance(...)

Main Components

ComponentPurpose
Proxy ClassGenerated proxy
InvocationHandlerHandles method calls

Example Flow

Client

Proxy Object

Real Object

Advantages

  • Flexible runtime behavior
  • Cross-cutting concerns
  • Reduced boilerplate

Types

  • JDK Dynamic Proxy
  • CGLIB Proxy

Important Interview Point:

JDK dynamic proxies work only with interfaces.


*54. Explain bytecode manipulation

Bytecode manipulation means modifying Java bytecode at runtime or build time.


Purpose

Used for:

  • dynamic code generation
  • AOP
  • profiling
  • instrumentation

Example Tools

  • ASM
  • Javassist
  • Byte Buddy
  • CGLIB

Workflow

Java Source

Bytecode (.class)

Modified Bytecode

JVM Execution

Common Use Cases

Use CaseExample
AOPSpring AOP
ORM EnhancementHibernate
MonitoringProfilers
MockingMockito

Advantages

  • Runtime flexibility
  • Dynamic enhancement
  • Framework support

Challenges

  • Complex debugging
  • JVM internals knowledge required

Important Interview Point:

Many modern Java frameworks internally use bytecode manipulation for dynamic behavior and performance optimization.

System Design & Backend

***55. How would you design a URL shortener?

A URL shortener converts long URLs into short unique URLs.

Example:

https://example.com/very-long-url

becomes:

https://short.ly/ab12

Core Requirements

Functional Requirements

  • Generate short URLs
  • Redirect to original URL
  • URL expiration support
  • Analytics support

Non-Functional Requirements

  • High availability
  • Scalability
  • Low latency

High-Level Architecture

Client

Load Balancer

Application Servers

Cache (Redis)

Database

URL Generation Techniques

TechniqueDescription
Counter + Base62Common approach
HashingMD5/SHA hashing
Random StringRandom unique keys

Example Base62

62 characters:
a-z, A-Z, 0-9

Database Design

Short URLOriginal URLExpiry
ab12long-urltimestamp

Performance Optimization

  • Redis caching
  • CDN
  • Database indexing
  • Asynchronous analytics

Challenges

  • Collision handling
  • Massive scale
  • Hot URLs

Important Interview Point:

Caching is critical because read operations are much higher than writes in URL shortener systems.


***56. How would you design a scalable chat application?

A scalable chat application should support:

  • real-time messaging
  • millions of users
  • low latency communication

Core Features

  • One-to-one chat
  • Group chat
  • Online status
  • Message delivery
  • Notifications

High-Level Architecture

Client Apps

Load Balancer

WebSocket Servers

Message Queue

Chat Services

Database + Cache

Communication Protocol

WebSockets

Used for:

Real-time bidirectional communication

Message Flow

Sender

Chat Server

Message Queue

Receiver

Storage

  • Recent messages → Redis
  • Permanent storage → Cassandra/MySQL

Scalability Techniques

  • Horizontal scaling
  • Distributed message brokers
  • Sharding
  • CDN for media

Reliability Features

  • Message acknowledgments
  • Retry mechanism
  • Offline message storage

Important Interview Point:

WebSockets are preferred over HTTP polling for real-time chat applications.


***57. How to improve Java application performance?

Java performance optimization involves improving:

  • CPU usage
  • memory efficiency
  • response time
  • throughput

Common Optimization Techniques

1. JVM Tuning

Adjust heap sizes:

-Xms
-Xmx

2. Use Efficient Data Structures

Example:

  • HashMap for fast lookup
  • ArrayList for random access

3. Minimize Object Creation

Avoid unnecessary temporary objects.


4. Use Connection Pooling

Reuse database connections.


5. Optimize Garbage Collection

Choose suitable GC:

  • G1 GC
  • ZGC

6. Caching

Store frequently accessed data in:

  • Redis
  • in-memory cache

7. Use Multithreading Carefully

Avoid:

  • excessive synchronization
  • thread contention

8. Database Optimization

  • indexing
  • query optimization
  • batching

Performance Monitoring Tools

ToolPurpose
JProfilerProfiling
VisualVMMonitoring
JConsoleJVM metrics

Important Interview Point:

Premature optimization should be avoided. Measure performance bottlenecks first.


***58. Explain caching strategies

Caching stores frequently accessed data temporarily for faster retrieval.


Why Caching is Needed

  • Reduce database load
  • Improve response time
  • Increase scalability

Common Caching Strategies

1. Cache Aside (Lazy Loading)

Application checks cache first.


Flow

Cache Miss

Read Database

Update Cache

Advantages

  • Simple
  • Efficient for read-heavy systems

2. Write Through Cache

Write goes to:

  • cache
  • database

simultaneously.


3. Write Back Cache

Write first stored in cache, later persisted to database.


4. Read Through Cache

Cache itself loads data from database automatically.


Eviction Policies

PolicyMeaning
LRULeast Recently Used
LFULeast Frequently Used
FIFOFirst In First Out

Popular Caching Technologies

  • Redis
  • Memcached
  • Ehcache

Important Interview Point:

Cache Aside is the most commonly used caching strategy in modern applications.


***59. Difference between Redis and Memcached

Both are in-memory caching systems but differ in capabilities.


Difference Table

FeatureRedisMemcached
Data StructuresRich supportKey-value only
PersistenceSupportedNot supported
ReplicationYesLimited
PerformanceVery fastExtremely fast
Memory UsageHigherLower

Redis Features

Supports:

  • strings
  • lists
  • sets
  • hashes
  • streams

Memcached Features

Simple:

Distributed key-value cache

Use Cases

RedisMemcached
Session storageSimple caching
Real-time analyticsLightweight cache
Queues/pub-subTemporary cache

Important Interview Point:

Redis is commonly preferred because of:

  • persistence
  • advanced data structures
  • replication support

***60. What is rate limiting?

Rate limiting controls:

Number of requests

a client can make within a specific time period.


Purpose

  • Prevent abuse
  • Protect servers
  • Improve security

Example

100 requests/minute

Common Algorithms

AlgorithmDescription
Token BucketTokens consumed per request
Leaky BucketFixed processing rate
Fixed WindowCounter-based
Sliding WindowMore accurate window

Example Use Cases

  • API protection
  • Login attempt control
  • DDoS prevention

Implementation Technologies

  • Redis
  • API Gateway
  • NGINX

Important Interview Point:

Rate limiting is essential for public APIs and microservices security.


**61. Explain API Gateway

API Gateway acts as:

Single entry point

for client requests in microservices architecture.


Responsibilities

FunctionPurpose
RoutingForward requests
AuthenticationValidate users
Rate LimitingPrevent abuse
Load BalancingDistribute traffic
LoggingMonitoring

Architecture

Client

API Gateway

Microservices

Advantages

  • Centralized security
  • Simplified client communication
  • Reduced client complexity

Popular API Gateways

  • Kong
  • NGINX
  • Spring Cloud Gateway

Important Interview Point:

API Gateway is a key component in microservices architecture.


**62. What is distributed locking?

Distributed locking ensures:

Only one process across distributed systems

can access a shared resource at a time.


Why Needed?

In distributed systems:

  • multiple servers may access same resource simultaneously

Example Use Cases

  • Payment processing
  • Inventory updates
  • Scheduled jobs

Common Implementations

TechnologyMethod
RedisRedLock
ZooKeeperEphemeral nodes
DatabaseRow locking

Example Flow

Server A acquires lock
Server B waits

Challenges

  • Deadlocks
  • Network partitions
  • Lock expiration

Important Interview Point:

Distributed locking is critical for maintaining consistency in distributed systems.


*63. Explain CAP theorem

CAP theorem states that a distributed system can guarantee only two out of three properties simultaneously.

Introduced by:
Eric Brewer


CAP Components

PropertyMeaning
CConsistency
AAvailability
PPartition Tolerance

1. Consistency

All nodes return same latest data.


2. Availability

Every request receives response.


3. Partition Tolerance

System continues working despite network failures.


Important Rule

In distributed systems:

Partition tolerance is mandatory

So tradeoff usually happens between:

  • Consistency
  • Availability

System Types

TypeFocus
CP SystemConsistency + Partition Tolerance
AP SystemAvailability + Partition Tolerance

Examples

DatabaseType
MongoDBAP
HBaseCP
CassandraAP

Real-World Meaning

During network partition:

  • choose correct data (Consistency)
    or
  • choose uninterrupted service (Availability)

Important Interview Point:

CAP theorem applies specifically to:

Distributed systems

Important Advanced Questions

***64. What are records in Java?

Records are a special type of class introduced to reduce boilerplate code for:

  • immutable data objects
  • DTOs
  • model classes

Introduced in:

Java 16

Purpose

Automatically generate:

  • constructor
  • getters
  • equals()
  • hashCode()
  • toString()

Example

record Employee(int id, String name) {
}

Equivalent Traditional Class

Would require:

  • fields
  • constructor
  • getters
  • equals/hashCode
  • toString

Features

  • Immutable by default
  • Concise syntax
  • Final class automatically

Accessing Values

Employee e =
new Employee(1, "Java");

System.out.println(e.name());

Advantages

  • Less boilerplate
  • Better readability
  • Ideal for data carriers

Limitations

  • Cannot extend other classes
  • Fields are final
  • Not suitable for mutable entities

Important Interview Point:

Records are best used for:

Immutable data transfer objects (DTOs)

***65. What are sealed classes in Java?

Sealed classes restrict which classes can inherit from them.

Introduced in:

Java 17

Purpose

Provide:

  • controlled inheritance
  • better domain modeling
  • safer APIs

Example

public sealed class Shape
permits Circle, Rectangle {
}

Allowed Subclasses

final class Circle extends Shape {
}

final class Rectangle extends Shape {
}

Subclass Modifiers

A permitted subclass must be:

  • final
  • sealed
  • non-sealed

Benefits

  • Better control over hierarchy
  • Improved maintainability
  • Enhanced pattern matching

Real-World Usage

Useful in:

  • financial systems
  • state machines
  • compiler design

Important Interview Point:

Sealed classes improve:

Type safety and controlled extensibility

***66. Explain virtual threads (Project Loom)

Virtual Threads are lightweight threads introduced by:

Project Loom

Available officially in:

Java 21

Purpose

Enable:

  • massive concurrency
  • simpler asynchronous programming
  • efficient thread management

Problem with Traditional Threads

Platform threads are:

  • expensive
  • memory-heavy
  • OS-dependent

Virtual Threads

Managed by JVM instead of OS.


Example

Thread.startVirtualThread(() -> {

System.out.println("Virtual Thread");
});

Advantages

  • Millions of concurrent threads
  • Lower memory usage
  • Simplified concurrency model

Use Cases

  • Web servers
  • High-concurrency APIs
  • Database operations

Difference Table

FeaturePlatform ThreadVirtual Thread
Managed ByOSJVM
Memory UsageHighLow
ScalabilityLimitedMassive

Important Interview Point:

Virtual threads simplify:

Thread-per-request architecture

without huge resource cost.


***67. What is reactive programming?

Reactive programming is an asynchronous programming paradigm focused on:

  • non-blocking execution
  • event streams
  • responsive systems

Main Goals

  • High scalability
  • Better resource utilization
  • Responsive applications

Core Concepts

ConceptMeaning
PublisherProduces data
SubscriberConsumes data
StreamFlow of events
BackpressureControl data flow

Example

Flux.just(1,2,3)
.subscribe(System.out::println);

Features

  • Asynchronous
  • Event-driven
  • Non-blocking I/O

Popular Reactive Libraries

  • Reactor
  • RxJava

Use Cases

  • Real-time systems
  • Streaming applications
  • High-traffic APIs

Important Interview Point:

Reactive programming improves scalability by reducing blocked threads.


***68. Difference between blocking and non-blocking I/O

These models define how applications handle I/O operations.


Blocking I/O

Thread waits until operation completes.


Example

Read file → Thread blocked

Features

  • Simpler programming model
  • More threads needed

Non-Blocking I/O

Thread continues execution without waiting.


Features

  • Better scalability
  • Efficient resource usage
  • Event-driven model

Difference Table

FeatureBlocking I/ONon-Blocking I/O
Thread BehaviorWaitsContinues execution
ScalabilityLowerHigher
Resource UsageHigherLower
ComplexitySimplerMore complex

Java APIs

APIType
java.ioBlocking
java.nioNon-blocking

Important Interview Point:

Reactive systems typically use:

Non-blocking I/O

**69. What is WebFlux?

Spring WebFlux is Spring’s reactive web framework introduced in Spring 5.


Purpose

Build:

  • reactive
  • asynchronous
  • non-blocking

web applications.


Based On

  • Reactor library
  • Reactive Streams specification

Main Reactive Types

TypeMeaning
Mono0 or 1 result
FluxMultiple results

Example

@GetMapping("/users")
public Flux<User> getUsers() {
return userService.getUsers();
}

Advantages

  • Better scalability
  • Efficient thread usage
  • Handles high concurrency

WebFlux vs Spring MVC

FeatureSpring MVCWebFlux
ModelBlockingNon-blocking
Thread UsageOne thread/requestEvent-loop model
ScalabilityModerateHigh

Important Interview Point:

WebFlux is best suited for:

  • streaming systems
  • high-concurrency APIs
  • reactive applications

**70. Explain Kafka integration with Java

Apache Kafka is a distributed messaging platform used for:

  • event streaming
  • real-time processing
  • asynchronous communication

Kafka Components

ComponentPurpose
ProducerSends messages
ConsumerReads messages
BrokerKafka server
TopicMessage category

Java Producer Example

KafkaProducer<String, String>

Java Consumer Example

KafkaConsumer<String, String>

Spring Kafka Example

@KafkaListener(topics = "orders")

Advantages

  • High throughput
  • Fault tolerance
  • Scalability
  • Durable messaging

Use Cases

  • Log processing
  • Event-driven systems
  • Real-time analytics

Important Interview Point:

Kafka is heavily used in:

  • microservices
  • event-driven architecture
  • distributed systems

**71. Explain Dockerizing Java applications

Dockerizing means packaging Java application and dependencies into:

Docker containers

Benefits

  • Environment consistency
  • Easy deployment
  • Scalability
  • Isolation

Basic Dockerfile Example

FROM openjdk:21

COPY app.jar app.jar

ENTRYPOINT ["java", "-jar", "app.jar"]

Build Docker Image

docker build -t myapp .

Run Container

docker run -p 8080:8080 myapp

Advantages

  • Portable deployments
  • Faster CI/CD
  • Simplified infrastructure

Best Practices

  • Use lightweight base images
  • Multi-stage builds
  • Externalize configurations

Important Interview Point:

Containerization is standard practice for:

  • microservices
  • cloud-native applications

*72. Explain Kubernetes basics for Java developers

Kubernetes is a platform used to automate:

  • deployment
  • scaling
  • management

of containerized applications.


Why Kubernetes is Needed

Managing containers manually becomes difficult at scale.


Core Kubernetes Components

ComponentPurpose
PodSmallest deployable unit
DeploymentManages pods
ServiceExposes application
ConfigMapExternal configuration
IngressExternal routing

Architecture

User

Ingress

Service

Pods

Kubernetes Features

  • Auto-scaling
  • Self-healing
  • Rolling updates
  • Load balancing

Java Developer Responsibilities

  • Containerize apps
  • Configure deployments
  • Monitor resources
  • Handle scaling

Example Deployment

apiVersion: apps/v1
kind: Deployment

Advantages

  • High availability
  • Better scalability
  • Automated deployment

Important Interview Point:

Kubernetes is widely used for deploying:

  • Spring Boot microservices
  • cloud-native Java applications
  • distributed systems