JVM & Performance Tuning
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
| Concept | Meaning |
|---|---|
| Visibility | Changes visible across threads |
| Atomicity | Operation completes fully |
| Ordering | Execution 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
| Feature | synchronized | Lock |
|---|---|---|
| Type | Keyword | Interface |
| Lock Release | Automatic | Manual |
| tryLock() Support | No | Yes |
| Fairness | No | Yes |
| Interruptible Lock | No | Yes |
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
| Method | Purpose |
|---|---|
| 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
| Class | Purpose |
|---|---|
| AtomicInteger | Atomic int operations |
| AtomicLong | Atomic long operations |
| AtomicBoolean | Atomic boolean operations |
| AtomicReference | Atomic 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
| Class | Purpose |
|---|---|
| ForkJoinPool | Thread pool |
| RecursiveTask | Returns result |
| RecursiveAction | No 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
| Method | Purpose |
|---|---|
| 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
| Feature | Starvation | Livelock |
|---|---|---|
| Thread State | Waiting indefinitely | Continuously active |
| Progress | No | No |
| CPU Usage | Low | High |
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
| Lock | Purpose |
|---|---|
| Read Lock | Multiple readers allowed |
| Write Lock | Exclusive 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
| Method | Purpose |
|---|---|
| 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
***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
| Feature | Purpose |
|---|---|
| IoC Container | Manages objects/beans |
| Dependency Injection | Loose coupling |
| AOP | Cross-cutting concerns |
| Spring MVC | Web development |
| Transaction Management | Database 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
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual | Auto-configuration |
| Server Setup | External server needed | Embedded server |
| Development Speed | Slower | Faster |
| Boilerplate Code | More | Less |
| Deployment | WAR | Executable 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
| Type | Description |
|---|---|
| Constructor Injection | Through constructor |
| Setter Injection | Through setter |
| Field Injection | Direct 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
| Scope | Description |
|---|---|
| singleton | Single object per container |
| prototype | New object every request |
| request | One bean per HTTP request |
| session | One 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
| Feature | Constructor Injection | Setter Injection |
|---|---|---|
| Dependency Type | Mandatory | Optional |
| Immutability | Better | Poor |
| Testing | Easier | Moderate |
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
| Component | Purpose |
|---|---|
| Aspect | Cross-cutting logic |
| Advice | Action performed |
| Join Point | Execution point |
| Pointcut | Matching 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
| Feature | JDBC | Hibernate |
|---|---|---|
| Level | Low-level API | ORM Framework |
| SQL Writing | Manual | Automatic |
| Boilerplate Code | More | Less |
| Caching | No built-in | Yes |
| Object Mapping | Manual | Automatic |
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
| Annotation | Layer |
|---|---|
| @Component | Generic |
| @Service | Business layer |
| @Repository | Persistence layer |
| @Controller | Presentation 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
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create data |
| PUT | Update data |
| DELETE | Remove 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.
***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
| Annotation | Purpose |
|---|---|
| @Override | Method overriding |
| @Deprecated | Marks obsolete code |
| @SuppressWarnings | Suppress compiler warnings |
Custom Annotation Example
@interface MyAnnotation {
}
Meta-Annotations
| Annotation | Purpose |
|---|---|
| @Target | Where annotation applies |
| @Retention | Annotation lifetime |
Retention Policies
| Policy | Availability |
|---|---|
| SOURCE | Compiler only |
| CLASS | Stored in bytecode |
| RUNTIME | Available 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
| Concept | Meaning |
|---|---|
| Immutability | Data does not change |
| Pure Functions | No side effects |
| Higher-Order Functions | Functions 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
| Method | Purpose |
|---|---|
| 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
| Feature | PermGen | Metaspace |
|---|---|---|
| Memory Type | JVM Heap | Native Memory |
| Resizing | Fixed | Dynamic |
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
| Component | Purpose |
|---|---|
| Proxy Class | Generated proxy |
| InvocationHandler | Handles 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 Case | Example |
|---|---|
| AOP | Spring AOP |
| ORM Enhancement | Hibernate |
| Monitoring | Profilers |
| Mocking | Mockito |
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
| Technique | Description |
|---|---|
| Counter + Base62 | Common approach |
| Hashing | MD5/SHA hashing |
| Random String | Random unique keys |
Example Base62
62 characters:
a-z, A-Z, 0-9
Database Design
| Short URL | Original URL | Expiry |
|---|---|---|
| ab12 | long-url | timestamp |
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:
-
HashMapfor fast lookup -
ArrayListfor 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
| Tool | Purpose |
|---|---|
| JProfiler | Profiling |
| VisualVM | Monitoring |
| JConsole | JVM 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
| Policy | Meaning |
|---|---|
| LRU | Least Recently Used |
| LFU | Least Frequently Used |
| FIFO | First 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
| Feature | Redis | Memcached |
|---|---|---|
| Data Structures | Rich support | Key-value only |
| Persistence | Supported | Not supported |
| Replication | Yes | Limited |
| Performance | Very fast | Extremely fast |
| Memory Usage | Higher | Lower |
Redis Features
Supports:
- strings
- lists
- sets
- hashes
- streams
Memcached Features
Simple:
Distributed key-value cache
Use Cases
| Redis | Memcached |
|---|---|
| Session storage | Simple caching |
| Real-time analytics | Lightweight cache |
| Queues/pub-sub | Temporary 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
| Algorithm | Description |
|---|---|
| Token Bucket | Tokens consumed per request |
| Leaky Bucket | Fixed processing rate |
| Fixed Window | Counter-based |
| Sliding Window | More 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
| Function | Purpose |
|---|---|
| Routing | Forward requests |
| Authentication | Validate users |
| Rate Limiting | Prevent abuse |
| Load Balancing | Distribute traffic |
| Logging | Monitoring |
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
| Technology | Method |
|---|---|
| Redis | RedLock |
| ZooKeeper | Ephemeral nodes |
| Database | Row 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
| Property | Meaning |
|---|---|
| C | Consistency |
| A | Availability |
| P | Partition 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
| Type | Focus |
|---|---|
| CP System | Consistency + Partition Tolerance |
| AP System | Availability + Partition Tolerance |
Examples
| Database | Type |
|---|---|
| MongoDB | AP |
| HBase | CP |
| Cassandra | AP |
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
| Feature | Platform Thread | Virtual Thread |
|---|---|---|
| Managed By | OS | JVM |
| Memory Usage | High | Low |
| Scalability | Limited | Massive |
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
| Concept | Meaning |
|---|---|
| Publisher | Produces data |
| Subscriber | Consumes data |
| Stream | Flow of events |
| Backpressure | Control 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
| Feature | Blocking I/O | Non-Blocking I/O |
|---|---|---|
| Thread Behavior | Waits | Continues execution |
| Scalability | Lower | Higher |
| Resource Usage | Higher | Lower |
| Complexity | Simpler | More complex |
Java APIs
| API | Type |
|---|---|
| java.io | Blocking |
| java.nio | Non-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
| Type | Meaning |
|---|---|
| Mono | 0 or 1 result |
| Flux | Multiple results |
Example
@GetMapping("/users")
public Flux<User> getUsers() {
return userService.getUsers();
}
Advantages
- Better scalability
- Efficient thread usage
- Handles high concurrency
WebFlux vs Spring MVC
| Feature | Spring MVC | WebFlux |
|---|---|---|
| Model | Blocking | Non-blocking |
| Thread Usage | One thread/request | Event-loop model |
| Scalability | Moderate | High |
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
| Component | Purpose |
|---|---|
| Producer | Sends messages |
| Consumer | Reads messages |
| Broker | Kafka server |
| Topic | Message 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
| Component | Purpose |
|---|---|
| Pod | Smallest deployable unit |
| Deployment | Manages pods |
| Service | Exposes application |
| ConfigMap | External configuration |
| Ingress | External 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