Showing posts with label SpringBoot. Show all posts
Showing posts with label SpringBoot. Show all posts

Tuesday, 11 August 2026

2026 Interview Preparations


====================

Java 8 vs Java 11 vs Java 21

====================

Java 8 : Lamda expressions, Functional Interfaces, Default and Static interfaces, Streams, Completable features and New Date and time functions are introduced


Java 11 :  Local Variable syntax changes in Lamda,  Enhanced Streams and Collections concepts and HttpClient is introducted 

Java 17 : 

Java 21 : Virtual Threads, Pattern Matching in switch, Record Patterns and SequencedCollection are introduced 


Java 25 : Collection Performance, Stream preformance, Concurrent & Runtime Performance and I/O Security Enhancements. 


Immutable Class : A class which is not having setters and who's instance cannot be change after they are created.

  • Declaring a final class 
  • Make all fields are private 
  • Make all fields are final.
  • Donot provide the setters. 
Advantages of Immutable class : 
  • Thread safety
  • Security & Consistency 
  • Reliable Hash keys

Multithreading : 

CompletableFuture vs Future : 

  • supplyAsync() — starting async tasks the right way (Java 8 CompletableFuture supplyAsync example) 
  • thenApply() & thenAccept() — transforming and consuming results (Multiple chained Futures cannot combined together using Future) 
  • thenCombine() — combining two futures into one (Multiple futures cannot combined together)
  • exceptionally() — exception handling in CompletableFuture (Poor exception handling in Future)
  • Chaining of futures vs combining futures — when to use each

Executor Service : 

Java supports Thread, Runnable, Callable and ExecutorService. In production, prefer managed executors instead of creating raw threads per task. In Java 21, virtual threads are a strong option for high-concurrency blocking I/O workloads.

Virtual Threads : 

Its a light weight threads which are managed by the JVM rather than OS. 
Its java 21 and Springboot 3.2+ onwards.
Platform Threads : Traditional OS Managed threads
Virtual Threads : JVM managed threads.

Virtual threads are useful at Async Processing by replacing the traditional thread pool executors with virtual thread exectuors in SpringBoot Async configuration. 

Advantages : 
  • Higher Concurrency 
  • Lower Memory Overhead
  • Better scalability for I/O bound operations 
Use Cases : 
  • API Gateway Parllel processing of larger datasets. 
  • Real time Systems like Chat applicatoins, Live Updates, Trackers 
  • I/O Bound operations like Database calls, HTTP requests, file Operations 
  • Handles millions of Concurrent Request. 


Microservices Design Patterns : 

Circuit Breaker DP : 

Circuit breaker implemented using Resillance4J and it has 3 components : CLOSED, OPEN and HALF-OPEN.

CLOSED : When failure rate threshold is below 

OPEN : When failture rate threshold is above 

HALF-OPEN : After wait durtaion it will go to HALF-OPEN

Circuit breaker uses two types of sliding windows to store and aggregate the outcome of calls. 

1. Count based sliding window

2. Time-based sliding window

Bulk Head Pattern : 2 types of SemaphoreBulkhead and FixedThreadPoolBulkhead 

Rate Limtter Design Pattern : Rate limiting is an imperative technique to prepare your API for scale and establish high availability and reliability of your service.

Retry Design Pattern : Just like the CircuitBreaker module, this module provides an in-memory RetryRegistry which you can use to manage (create and retrieve) Retry instances.

Saga Design Pattern : 

Event Driven Approach Design Pattern : 

  • Kafka based event driven approach

Database Design Pattern : 

Indentity Design Pattern : Security Identity Management (verifying who is making requests) and Domain Data Identity (how data entities maintain their identifiers across service boundaries)


Feign Client vs Rest Client : 

The primary difference is that Feign Client is declarative (you write an interface and let the framework generate the HTTP code), while a Rest Client is programmatic/fluent (you manually write the steps to build and execute the request).

Microservice vs Monolithic : 

A monolithic architecture consolidates all software components into a single program, whereas a microservices architecture divides the application into separate, self-contained services.

When to Use Microservices

Microservices are advantageous for certain types of projects:

  • Complex Systems

  • Scalability

  • Technology Diversification

  • Autonomous Teams: For bigger organizations with multiple teams that need to work independently.

Challenges while using Microservices : 
  • Database per service
  • Data inconsistency 
  • Integrate Testing
How Microservies communicate each other :
  • Synchronous
  • Asynchronous
  • Restful api's
  • Event Based communication
  • Database per service
  • API-Gateway

How would you decompose a monolithic application into microservices?

  • Identify Domains
  • Service Boundaries
  • Data Segrigation
  • Decouple services

Kafka Based Interview Questions :

Kafka consumer vs Consumer Group : 

  • Kafka consumer reads the data from the topic
  • Consumer group is a set of consumers work together and reads one or more topics.
OffSet : 
  • Offset is a unique sequential identifier record with in a partition.
  • Kafka tracks the offset per partition, per consumer group. So each group can consumes its own position.
How does kafka handles data retention : 
  • Retention can be time based, once it reaches to limit old message will be discarded.
  • Retention limit will be provided while creating the kafka clusters.
How Kafka ensure the data consistency : 
  • Replication : Each partition is replicated across the mulitple brokers 
  • Acknowlegements : Producers can wait for leaders only
  • Atomic, orders writes to a partition
  • Idempotent producers to prevent duplicate writes on retry.
KRaft :
  • To manage the metadata management kafka introduced the KRaft by removing the dependency on Apache ZooKeeper.
How to fix the lag issues in Kafka : 
  • Increase the Partition count 
  • Add more consumers instances : 
  • Ensure 1:1 Ratio : Align the no of active consumers with no of topic partitions.


Streams

Parllel Stream vs Stream : 
Streams : 
  • Run's single thread and results are predictable
  • Sequential
  • Low overheaded
                
Parllel Streams : 
  • Run's on multi threaded and results are unpredictable.
  • Parllel
  • High Overheaded due to thread management.

Map vs Flat Map : 

Map : 
  • One to one mapping 
  • To use basic data transformation

FlatMap : 
  • One to Many (zero)mapping
  • To handling collection of collections 
Tweleve-Factor App Concepts in java : 
  1. CodeBase
  2. Dependencies
  3. Configuration 
  4. Backing services 
  5. Build, Release, Run
  6. Processes
  7. Port Binding
  8. Concurrency 
  9. Disposability
  10. Dev/Prod Parity 
  11. Logs
  12. Admin Process

AWS Interview Questions : 

What is Cloud Computing : 
Cloud computing provides on-demand access to IT resources like compute, storage, and databases over the internet.

3 Types of Cloud Computing : 

  1. SAAS (Software as a service) : Aws email service etc services by AWS.
  2. PAAS (Platform as a service) : Elastic Beanstalk, Heroko.
  3. IAAS (Infrastructure as a service) : EC2 instance, S3 Storage, VPC.

EC2 Instance : Elasic Cloud Computing
  • Scalable virtual servers called instances in AWS
  • EC2 instances are used to host websites 
  • Run batch job process to acheive scalability

S3 Storage : 

  • Simple Storage Service 
  • Stores the objects in secure way
IAM : 
  • Identity Access Management
  • Helps you to securely access to AWS services 
  • IAM allows us to manage users & Roles.
RDS : 
  • Relational Database Service
  • To Manage the database service
VPC : 
  • Virtual Private Network
  • To create a virtual network in AWS.
AWS Cloud Watch : 
  • Uses for monitoring purposes
  • Metrics, Alarms, Logs, Events 
AWS Lamda : 
  • Server less Compute service
ELB : Elastic Load Balancer
EBS : Elasic Bean Stalk

Blue Green Deployment : 
  • Blue means current version deployment
  • Green means new version deployment
ECS : Elastic Container System 
  • Replacement to kubernetes, this simplifier to run EC2 Instances.
AWS Code Build : Compile the code, run tests, produce deployable artificats 
AWS Code Deploy : Deploy into AWS Environment
AWS Code Pipeline : Automate the deployment process using CICD workflow.

Amazon ECS : Deploying the Docker based applications into ECS Containers. 
AWS Secrets : Maintain the sensitive information into secret manager service.

Migrating the Old Application into New Applicaiton in AWS : 
  • Must follow the 7 Rs Framework 
  1. Rehost
  2. Replatform
  3. Repurchase
  4. Refactor
  5. Retire
  6. Retain
  7. Relocate 
  • Used EC2 and RDS to migrate also important.

DataStructures : 

  • Array
  • String
  • Linked List
  • Queue
  • Stack
  • Tree 
  • Graph
  • Hashing

SpringBoot ::

Spring Boot Scopes:: 
  • Singleton
  • Prototype
  • Request
  • Session
  • Application 
  • Websocket
Exceptino Handling : 

CustomException :: 

A custom exception is a class created by the developer to represent a specific error in the application.


Examples: Invalid account number, Insufficient balance, Payment failed, Flight not found

Serilization vs De-Serialization ::


HashMap Internally working technique :: 


When we will do the HashCode and Equals() : 

when ever both the string object values are same then we will use hashcode and equals().


What is a functional interface? 

 A functional interface has exactly one abstract method and can be used as the target of a lambda or method reference.

why are Streams usually faster than loops for large data?

Streams use internal optimizations like: Stream Pipeline

• Lazy ovaluation

• Mothod chaining 

•Built-in parallel proconcing

Syncrnonization :: 

Bad practise of synchronization : synchronizing on the boxed type Integer:

private int count = 0;

private final Integer intLock = count;  // the solution for synchronization on the boxed primitive is to create a new instance. private final Integer intLock = new Integer(count);

public void boxedPrimitiveBadPractice() { 

    synchronized (intLock) {

        count++;

        // ... 

    } 

}


Why does HashMap allow one null key and multiple null values ? 

HashMap is docignod to handle null gracofully. It treats null key's hashCode as O and stores it in bucket O. Multiple null values are allowed because values are not used in hashing or key comparison.





Tuesday, 6 February 2018

Spring Boot

Spring Boot is a framework which have Auto Configuration, Auto Dependency Resolution and Embedded HTTP Server like Tomcat and Jetty.

Spring Boot main aim is "To simplify the Spring Based Application Development".

To Start the Spring Boot Application below Jars are required.
  • SpringBootStarterWeb
  • SpringBootStarterParent
  • Java8Version
  • SpringBoot Maven Plugin.
Pros : 
  • No need to write XML Configurations, all configurations we can write in java code.
  • Reduces the Boilerplate code.
  • Testing is very easy.
  • Quick starts of application.
  • Provides all non functional features like Embedded Server, Security, Matrix and healthchecks.
  • Provides lot of plugin to work with Embedded Systems.
  • Provides Command Line Interface (CLI) Tool for development and testing.
Cons : 
  • Very tough to convert the legacy projects into new Projects.
Spring Boot Jars & uses : 
  • Spring-Boot-Starter-Web-Service : We can work with SOAP Web Services.
  • Spring-Boot-Starter-test : For Junit and MOCITO etc.
  • Spring-Boot-Starter-jdbc : For Spring JDBC
  • Spring-Boot-Starter-Security : Spring Security
  • Spring-Boot-Starter-data-JPA : JPA
  • Spring-Boot-Starter-data-rest : Restful WebServices.
  • Spring-Boot-Actuator : To load the Matrices and Project Health checkups.
More Points About Spring Boot : 

  • Spring Boot Starter Web Jar : It includes Tomcat, Hibernate, Restful Service, Logging and Web jars.
  • Spring Boot Auto Configuration : It will have Auto mated Error pages. Automatically Error page will come if we hit wrong URL. 
  • @ Spring Boot Application : Will include @EnableAutoConfiguration, @Configuration, @ComponentScan.
@SpringBootApplication :

@Configuration : Denotes the bean definitions for application context.
@EnableAutoConfiguration : It enables the bean presents in class path settings and various property settings.
@ComponentScan : It tells to spring scan all the components like configurations and services and other components in the application.

Spring-boot-starter-cache : 
Enabling spring framework Caching support.
@EnableCache :
Load Changes without Restart the Server : 
  • By using Spring-boot-devtools Dependency we can load the changes and it will reflect without restarting the server.
Spring-Boot-Actuator : 
  • It uses to load the Matrics and Health Checkups for application.
  • Basically it will uses in Production environment only.
  • By using " Spring-Boot-Actuator" Jar we can use this service.
Run with Custom Port : 
  • Add the following port in application.properties file
server.port = 8091

Spring Boot Remote Application :
  • By using below configuration, we can run the Spring Boot Application Remotely.
spring.devtools.remote.sercret = mysecret
Validations in Spring Boot :
  • By using below annotations we can validate 
@ConfigurationProperties , @Value 
Spring-Boot-Starter-Quartz : 
  • We can schedule the cron jobs by using Spring-Boot-Starter-Quartz.
HIKARI Connection Pool in Spring Boot :
Step 1 : Add a "hikaricp 2.6.1 jar" or "latest hikari jar" as dependency in pom.xml.
Step 2 : Add a below property in application. properties file.
spring.datasource.type = com.zaxxer.hikari.HikariDataSource
Step 3 : Set all Hikari properties in properties file like timeout etc.
Step 4 : Use HikariDataSource.
Step 5 : Set all the properties in util class or configuration class.
             private static HikariDataSource ds = new HikariDataSource();
             ds.setDriverName("");
             ds.setJdbcUrl("");
             ds.setUserName("");
             ds.setPassword("");

Proc of HikarCP : 
  • Its very faster and zero overhead production quality connection pool.
Override the Embedded server in Spring-boot :
Step 1 : Exclude the tomcat dependency in Spring-boot-starter-web by using below exclusion.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>



Step 2 : Change the default server port number.
Step 3 : Change the Server-specific properties.(SSL, ContextPath, ContextParameter etc.)

How to provide security in Spring Boot :
Use Spring-Boot-Starter-Security in pom.xml and in configuration file extends the WebSecurityConfigurerProperty class and override the methods.

How to provide the security for REST URL or URI or API :
In Different ways we can provide the Security for Rest API's : 
  1. Basic authentication (SSL Certificate) : Client will provide the SSL Certificate and install it in Web Server.
  2. OAUTH 1.0a : OAUTH is signature based protocol.  This protocol uses Cryptography signature. This can be used without SSL.
  3. OAUTH 2 : This protocol completely eliminates the signature. It requires Transport layer security which handles the encryption. This is very simple to configure so this will use for less sensitive data.
Because of above adv and disadvantages it is safer and simpler to choose basic Auth with SSL Cert for Most REST Services

ActiveMQ in SpringBoot :
By using "Spring-boot-starter-activemq" jar in pom.xml.

In Spring Boot How it will take Hibernate as default implementation of JPA :
First Need to add Spring-Boot-Starter-Data-JPA dependency in pom.xml file.

Once Spring Boot application starts it will check the class-path. If Hibernate dependency in the class path then Spring boot will take as default implementation of JPA. If it is H2 database related Jars in class-path then we can write the H2 implementation for JPA. 

How do we connect the external database in Spring Boot :
Remove H2 database jar or Hibernate jar in pom.xml or make it SCOPE as test. Add the Other external Database jar (MySql or Oracle) into pom.xml and configure the properties in Configuration class file and add the properties in property file.

Profile In Spring Boot : 
Enterprise applications will have multiple environments like DEV, STAGE, PROD.
So Profile will help to have different application configuration for different environments.
Profile Configuration :
We are having 2 profiles : Dev and Prod
Step 1 : Override the property file name like below
Dev : application-dev.properties
Prod : application-prod.properties

Step 2: Once we have a specific profile configuration we have to set the Active profile.
2 way we can do this. 
1. By changing the property in applicaiton.properties file.
spring.profile.active = prod
2. By changing the arguments in environment.
-Dspring.profile.active = prod


More Points will be add soon...

Omniroute step by step setup

 Omniroute step by step setup Step 1 : Install node js and omniroute using below command.  npm install -g omniroute Step 2 : Start the ser...