Senior Java Developer Interview Questions

Core Java

1. Internal working of ConcurrentHashMap in Java 8

ConcurrentHashMap uses segmentation with buckets padded to reduce false sharing, and uses CAS-based synchronization for updates within a bucket. In Java 8, the locking mechanism moved from segment-based to a bin-level lock using Node and TreeBin objects, supporting higher concurrency and efficient resizing.

2. Difference: synchronized, ReentrantLock, ReadWriteLock
  • synchronized is a basic JVM keyword, simple but inflexible (no tryLock, no fairness).
  • ReentrantLock allows manual lock/unlock, supports tryLock, fairness, interruptibility.
  • ReadWriteLock (with ReentrantReadWriteLock) supports multiple reads, single write at a time, improving performance for mostly-read scenarios.
3. Java memory leak handling and detection

Java uses garbage collection to reclaim unused objects, but leaks happen with lingering references. Detecting leaks involves analyzing heap dumps (using tools like VisualVM, YourKit), monitoring GC logs, and profiling the application for rising memory usage.

4. Thread-safe Singleton in Java

Best approach is a static inner class or using an enum:

public enum Singleton { INSTANCE; }

Another is double-checked locking with a volatile instance.

5. Java memory model and GC tuning

Java memory model includes heap (objects), stack (threads), metaspace (class metadata). GC tuning includes choosing collector (G1, CMS, ZGC), sizing heap/metaspace, and GC log analysis; parameters like -Xmx, -XX:MaxMetaspaceSize, and tuning options help balance pause time vs throughput.

Spring & Spring Boot

6. Dependency injection internals in Spring

Spring creates and wires beans via ApplicationContext and BeanFactory, instantiating and injecting dependencies using reflection and proxies. The wiring can be constructor, setter, or field-based, with lifecycle managed by the container.

7. Spring Boot starters vs manual dependency management

Spring Boot starters provide curated, compatible dependency sets for specific features (web, JPA, etc.), easing configuration. Manual management requires adding/maintaining all libraries and versions independently, increasing risk of conflicts.

8. Idempotency in REST APIs

Achieved by tracking request identifiers and ensuring repeated requests yield the same outcome. Use idempotency keys (in request headers) combined with persistent storage to check and process requests only once.

9. Handling huge traffic in Spring Boot APIs
  • Connection pooling (HikariCP for DB connections)
  • Caching (Redis, Caffeine)
  • Asynchronous calls (CompletableFuture, @Async)
  • Load balancing and horizontal scaling
10. Securing AWS-hosted APIs: IAM, Cognito, JWT
  • IAM roles: Attach to EC2, ECS, Lambda for permission management.
  • Cognito: User authentication, OIDC tokens.
  • JWT: Use Spring Security to parse JWTs, validate claims, and authorize requests.

JPA / Hibernate

11. Optimizing large batch inserts/updates

Use session.flush() and session.clear() periodically, disable 2nd-level cache, and leverage batch size settings (hibernate.jdbc.batch_size). Prefer stateless session for large batches.

12. Entity graphs vs fetch joins
  • Entity graphs allow dynamic fetch plan without altering JPQL.
  • Fetch joins fetch related entities in a single query, but can cause Cartesian products if not used carefully.
13. Hibernate 2nd Level Cache and providers

Stores entities beyond session for cross-session reuse. Common providers: Ehcache, Redis, Hazelcast, Infinispan. Configure via cacheRegionFactory and enable caching on entities.

14. Optimistic locking failure handling

Catch OptimisticLockException, reload entity, retry business logic, or show user a conflict message.

15. Tuning JPA-generated SQL queries

Optimize with custom queries (JPQL or native), query hints, profiling logs, and index creation.

Microservices & Architecture

16. Orchestration vs choreography
  • Orchestration: Central controller/workflow engine (e.g., Camunda), direct commands.
  • Choreography: Services interact via events (Kafka, SQS), with decentralized control.
17. Handling distributed transactions at scale

Saga pattern splits transactions into steps with compensations if failures occur. Outbox pattern writes events to DB as part of the transaction, later published to broker.

18. API throttling, rate limiting, request bursting
  • Throttling controls max requests in a time window.
  • Rate limiting enforces quotas (leaky bucket, token bucket).
  • Request bursting allows short-term traffic spikes within limits.
19. High-availability, fault-tolerant microservice design

Key elements: stateless services, redundancy, auto-scaling, health checks, failover, circuit breakers, retries, data replication.

20. Event-driven architecture example

Kafka: Microservices publish/subscribe to topics, decoupling producers/consumers; enables async processing. AWS SQS/SNS for queue/topic notification.

Cloud & DevOps Basics (AWS Focus)

21. AWS EC2 vs ECS vs EKS vs Lambda
ServiceDescription
EC2VM compute; host anything
ECSDocker container orchestration
EKSManaged Kubernetes
LambdaServerless functions
22. Securing secrets and credentials in AWS

Use AWS Systems Manager Parameter Store or AWS Secrets Manager for encrypted secret storage and retrieval; never hardcode secrets.

23. Blue/green or canary deployments on AWS

Implement using CodeDeploy, ECS/EKS rolling updates, or Lambda aliases. Route small traffic to new version (canary); shift all traffic after validation (blue/green).

24. Logging, tracing and monitoring

CloudWatch for logs and metrics, X-Ray for distributed tracing, ELK stack (Elasticsearch, Logstash, Kibana) for deep log analysis.

25. Auto Scaling Groups vs Kubernetes HPA
  • ASGs (EC2): Scale VMs based on metrics.
  • HPA (K8s): Scales pods based on resource utilization.

DSA & System Design (Amazon Focus)

26. Rate limiter design (Amazon API Gateway)

Token bucket or leaky bucket algorithm; store token count in Redis or in-memory; reject requests over quota.

27. Cache system with expiration and eviction policy

Design around a hashmap with doubly-linked list for LRU tracking; support TTL per entry.

28. Finding top 10 URLs in S3 log file efficiently

Use AWS Athena or EMR (Spark) to process logs; stream, aggregate, and keep a min-heap of top URLs.

29. Merging two sorted data streams in real time

Read head of both streams, compare, emit lowest, advance pointer; use priority queue if merging >2 streams.

30. Thread-safe LRU cache in Java

Wrap LRU cache (LinkedHashMap) with Collections.synchronizedMap or use ConcurrentHashMap + custom logic for order maintenance.

Behavioral / Leadership Principles

31. Disagreement with manager

A manager and I had different views on technical debt vs. new features; I gathered data, showed business impact, discussed trade-offs, and reached a consensus.

32. Delivered results under tight deadlines

On a mission-critical release, I identified priorities, delegated effectively, worked extra hours, and streamlined processes to deliver on time.

33. Improved process or system

Noticed frequent build failures; automated CI pipeline, reduced manual steps, improved team productivity.

34. Handling project failure

Analyzed root cause, accepted responsibility, communicated transparently, documented learnings, prevented recurrence.

35. Influenced team without authority

Facilitated knowledge sharing, led by example, and built consensus by demonstrating value, earning voluntary support from peers.

Post a Comment

Previous Post Next Post