Interview Quation

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 15

Quations :

1. how to find out memory leaks in application and prevent? tools to see memory
leaks ?
--> using JProfiler - JProfiler provides interfaces for viewing system
performance, memory usage, potential memory leaks, and thread profiling.
--> IntelliJ Profiler
--> Java Visual VM
--> verbose:gc - By enabling verbose garbage collection, we can track the
detailed trace of the GC. To enable this.
--> Eclipse Memory Leak Warnings
--> by doing Code Reviews

--> Preventing - Avoid Static instance , Unclosed Resoruce, Equals and


hashcode methods ,
Inner Classes That Reference Outer Classes,Through finalize() Methods,
ThreadLocals,

2. Where do we define code coverge check list? and what are the main check list?
Doing with inteliJI : https://www.jetbrains.com/help/idea/creating-custom-
inspections.html
Doing in Sonar Qube:
.Create a SonarQube plugin.
.Put a dependency on the API of the language plugin for which you are writing
coding rules.
.Create as many custom rules as required.
.Generate the SonarQube plugin (jar file).
.Place this jar file in the SONARQUBE_HOME/extensions/plugins directory.
.Restart SonarQube server.

Main Checklist:
.Functional Requirement : does code meet all requirments wich it should meet.
.Side effect on existing code : Sometimes one change in your system may cause
a bug in other upstream and downstream systems
.Concurrency : code is thread-safe? Does it have properly synchronized if
using the shared resources?
.Readability and maintenance: Does the code is readable? Or is it too
complicated
.Consistency: same function should use
.Performance:loop or multiple times optimize the code which is going to
execute more often.
.Error and Exception handling:
.Simplicity:
.Reuse of existing code
.Unit Test covered for all functions

3.how to handle load balance and where we need mention ? azure cloud/Aws cloud /
spring boot?

Load balancing is the process of distributing traffic among different


instances of the same application.
There are many algorithms when it comes to load balancing:
Random selection: Choosing an instance randomly
Round-robin: Choosing an instance in the same order each time
Least connections: Choosing the instance with the fewest current connections
Weighted metric: Using a weighted metric to choose the best instance (for
example, CPU or memory usage)
IP hash: Using the hash of the client IP to map to an instance
Note :if we choose Ribbon by default round robbin load balnce will work, no
need any extra work.

4.how to handle rollback transaction in microservices ?


Common solution for distributed transaction scenarios in micro-service
architecture is the Saga pattern. Distributed sagas is a pattern for managing
failures in scenarios as the one that you have described.
1. Action you would publish an event like "removeOrder" in order to remove
the reservation and revert the state back to the state as it was before the
transaction for that Business process started.

5.What is index file in Kafka?


The index file contains the exact position of a message in the log file for
all the messages in the ascending order of the offsets.

6.How does the server know if a JWT is valid?


When your authentication server receives an incoming JWT, it uses the
incoming JWT's header and payload segments and the shared private key to generate a
signature. If the signature matches, then your application knows that the incoming
JWT can be trusted.

7.How to create image for microservice in springboot?


In SpringBoot application - > Need to create one Dockerfile -> after build -
> In terminal -run the command as- docker build
Dockerfile:
-----------
FROM openjdk:11
ADD target/springboot.jar springboot.jar
EXPOSE 8080
ENTRYPOINT["java", "-jar", "springboot.jar"]

8.Diff bw POST and PUT and PATCH rest api?


Create resorce - POST
Read resorce - GET
Update resorce- PUT
Delete resorce - DELETE
If you only need to update one field - PATCH

9.How to create bean in SpringBoot?


Creating Bean Inside an XML Configuration File (beans.xml)
Using @Component Annotation
Using @Bean Annotation

10.Diff bw @Component and @Bean ?


@Component auto detects and configures the beans using classpath scanning
@Bean explicitly declares a single bean, rather than letting Spring do it
automatically.
@Component has different specializations like @Controller, @Repository and
@Service whereas
@Bean has no specializations.

11.AWS lambada?
AWS Lambda is an event-driven, serverless computing service that lets you run
code without provisioning or managing servers. With Lambda, you can upload your
code as a ZIP file or container image, and Lambda automatically and precisely
allocates compute execution power and runs your code based on the incoming request
or event. You can write Lambda functions in your favorite language (Node.js,
Python, Go, Java, and more) and use both serverless and container tools, such as
AWS SAM or Docker CLI, to build, test, and deploy your functions.
12.which AWS service are used ?
https://www.eginnovations.com/blog/top-10-aws-services-explained-with-use-cases/
AWS lambada
AWS DynamoDB – NoSQL Database Services
AWS EKS – Elastic Kubernetes Service

13.Diff bw comparable and comparator ?


Comparable - compareTo(); no need to override method and it will give natural
order - using this
comparator - compare(); need to override method and compare multiple elements bw
two objects
class objects would be sorted depending on a single field of the class, and also
anticipate the same in future, and this requirement will not change, then it is
recommended to use the comparable interface.
If there is a requirement for sorting class objects through multiple fields, then
it is recommended to use the multiple comparator class explicitly.

14.REST API STATUS codes and examples ?


5XX codes used for telling the client that even though the request was fine, the
server has had some kind of problem fulfilling the request. On the other hand,
4XX codes are used to tell the client that it has done something wrong in
request
2xx sucess messages
1xx: Informational – Communicates transfer protocol-level information.
3xx: Redirection – Indicates that the client must take some additional action in
order to complete their request.

15.Diff bw classNotFoundException, noClassDefinationException ?

ClassNotFoundException occurs when you try to load a class at runtime using


Class.forName() or loadClass() methods and requested classes are not found in
classpath

noClassDefFoundError occurs when the class was present during compile time
and the program was compiled and linked successfully but the class was not present
during runtime. It is an error that is derived from LinkageError

16. how many types of classloders in java ?

Bootstrap Class Loader – It loads JDK internal classes. It loads rt.jar and
other core classes for example java.lang.* package classes.
Extensions Class Loader – It loads classes from the JDK extensions directory,
usually $JAVA_HOME/lib/ext directory.
System Class Loader – This classloader loads classes from the current
classpath. We can set classpath while invoking a program using -cp or -classpath
command line option.

17. how stream works internaly?


Phases of Stream :
Split: usually call it stream source.
Apply: Operations in this phase are called intermediate operations.
Combine :Completion with a terminal operation where the stream gets
materialised.

Stream works internaly using Linkedlist structure and in its internal storage
structure, each stage gets assigned a bitmap that follows this structure:
SIZED The size of the stream is known
DISTINCT The elements in the stream are unique, no duplicates.
SORTED Elements are sorted in a natural order.
ORDERED Wether the stream has a meaningful encounter order; this means that the
order in which the elements are streamed should be preserved on collection.
bitmap expl like : 1010

18. Difference between Map and Flatmap?


map() can be used where we have to map the elements of a particular collection
to a certain function, and then we need to return the stream which contains the
updated results.
List of fruit-[Apple, mango, pineapple, kiwi]
List generated by map-[5, 5, 9, 4]
exp: List list = fruit.stream()
.map(s -> s.length())
.collect(Collectors.toList());

flatMap() can be used where we have to flatten or transform out the string, as
we cannot flatten our string using map(). Produce a stream of stream value.
List of list-[[1, 2], [3, 4], [5, 6], [7, 8]]
List generate by flatMap-[1, 2, 3, 4, 5, 6, 7, 8]
EXP : List<Integer> flatList
= number.stream()
.flatMap(list -> list.stream())
.collect(Collectors.toList());

19.Diff bw JWT and OAuth?


JWT : is token based authentication machanism and user for Authentication &
Authorization. used for single page apps/mobile apps.
OAuth: is Protocal for authorization and authontication in web and mobile apps,
it is centralized Authorization serve and user for Authorization not for
Authontication and this for external API's are services.

20. What is api gate way ? how many api gateways are availble ?
API Gateway acts as a mediator between client applications and backend services
in microservices architecture
Microsoft Azure API Management, Kong Gateway

21.difference between synchronous and asynchronous services ?


Async is non-blocking, which means it will send multiple requests to a
server.
Sync is blocking — it will only send the server one request at a time and
will wait for that request to be answered by the server

22. what is kafka and topic?


Kafka topics are the categories used to organize messages. Each topic has a
name that is unique across the entire Kafka cluster.producers write data to topics,
and consumers read data from topics. Kafka topics are multi-subscriber

23 what is index file in kafka ?


The index file contains the exact position of a message in the log file for
all the messages in the ascending order of the offsets.

24.How to create springbatch job and springbatch time interval ?

https://docs.spring.io/spring-framework/reference/integration/scheduling.html#
@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should run on weekdays only
}
@Async
void doSomething() {
// this will be run asynchronously
}

24.how to connect with kafka from your microservice application ?

@Component
public class Consumer {
@KafkaListener(topics = "test")
public void processMessage(String content){
System.out.println("Message received: " + content);
}
}
application.prop
----------------
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=myGroup

spring.kafka.producer.bootstrap-servers: localhost:9092
spring.kafka.producer.key-serializer:
org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer:
org.apache.kafka.common.serialization.StringSerializer
---------------------------
Multiple consumers in the same consumer group
@Component
public class Consumer {
@KafkaListener(topics = "test", concurrency = "2" groupId = "myGroup")
public void processMessage(String content) {
System.out.println("Message received: " + content);
}
}
----------------------------------------------
@Service
public class Producer {

private static final Logger LOGGER =


LoggerFactory.getLogger(Producer.class);

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

public void sendMessage(String message){


LOGGER.info(String.format("Message sent -> %s", message));
kafkaTemplate.send(AppConstants.TOPIC_NAME, message);
}
}

25.Diff bw foreignKey and primaryKey.


A primary key is used to ensure that data in the specific column is unique. A
column cannot have NULL values, primary is one in table.
It is a column (or columns) that references a column (most often the primary key)
of another table. Whereas more than one foreign key is allowed in a table.

26. how to change propeties values dynamicaly at runtime in springboot ?


SpringApplication application = new
SpringApplication(Demo40Application.class);
Properties properties = new Properties();
properties.put("server.port", 9999);
application.setDefaultProperties(properties);
application.run(args);

27.how does knows client JWT token, how they validate ?


Validate the token by extracting username and expiration date from the token

//Getting token details


final String requestTokenHeader = request.getHeader("Authorization");
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
}

jwtTokenUtil.validateToken(jwtToken, userDetails)

//validate token
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !
isTokenExpired(token));
}

28.diff bw @pathvariable and @Query paramaters ?


Path variable : GET /employee/{id} - we can have resource with @PathParam
Query Param : GET /employee?start=1&size=10 - for filter or if you have any fixed
list of options

29.diff bw class variables and member variables and instance variable?


Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block. Instance
variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
Member variables are known as instance variables in java. Instance variables are
declared in a class, but outside a method, constructor or any block

30. how to find employee details, finding groupBY department ?


employeelist.stream().collect(Collectors.groupBY(Employee::getDepartment()));

31.kafa master broker and slave broker ?


Kafka works on the master-slave architecture similar to what most other
distributed services like HDFS and hadoop components are based out of.
Master node is commonly known as Leader while Slaves are referred to as
Brokers.
https://www.linkedin.com/pulse/apache-kafka-high-level-architecture-key-
components-madhukar-jaiswal/

32.kafka Working on which architecure ?


Single-Event Processing Pattern: In this design pattern, we use in our common
real-time use case of aggregating the data, data processing, and decision-making
types of streams. We can consider this patent as a map filter, which maps and
cleans the unrecognized events

Kafka provides log aggregation, stream processing, commit logs, and


clickstream tracking. Kafka is comprised of brokers, controllers, partitions,
consumers, producers, topics, schema registries

33.Saga Desin pattren ? types ?


The Saga design pattern is a way to manage data consistency across
microservices in distributed transaction scenarios. A saga is a sequence of
transactions that updates each service and publishes a message or event to trigger
the next transaction step.

There are two type of saga implementation ways, These are “choreography” and
“orchestration”.

Choreography Saga Patter


-------------------------
Choreography provides to coordinate sagas with applying publish-subscribe
principles. With choreography, each microservices run its own local transaction and
publishes events to message broker system and that trigger local transactions in
other microservices.

Orchestration Saga Pattern (Single point of failure)


---------------------------
Another Saga way is Orchestration. Orchestration provides to coordinate sagas
with a centralized controller microservice. This centralized controller
microservice, orchestrate the saga workflow and invoke to execute local
microservices transactions in sequentially.
The orchestrator microservices execute saga transaction and manage them in
centralized way and if one of the step is failed, then executes rollback steps with
compensating transactions.

34. Enterprise Integartion pattrens and how type framerworks availble ?


https://www.youtube.com/watch?v=u-vnD6NecjU
https://www.baeldung.com/spring-integration
Spring Integration, Mule, Apache Camel

35.What is the difference between Kafka and RabbitMQ?


RabbitMQ and Apache Kafka move data from producers to consumers in different
ways. RabbitMQ is a general-purpose message broker that prioritizes end-to-end
message delivery. Kafka is a distributed event streaming platform that supports the
real-time exchange of continuous big data.

36. Kafaka vocabluray?

Producer: A producer is a client that sends messages to the Kafka server to the
specified topic.
Consumer: Consumers are the recipients who receive messages from the Kafka
server.
Broker: Brokers can create a Kafka cluster by sharing information using
Zookeeper. A broker receives messages from producers and consumers fetch messages
from the broker by topic, partition, and offset.
Cluster: Kafka is a distributed system. A Kafka cluster contains multiple
brokers sharing the workload.
Topic: A topic is a category name to which messages are published and from
which consumers can receive messages.
Partition: Messages published to a topic are spread across a Kafka cluster
into several partitions. Each partition can be associated with a broker to allow
consumers to read from a topic in parallel.
Offset: Offset is a pointer to the last message that Kafka has already sent
to a consumer.

37. how will you find your exact request in distributed enivroment?
Implement microservices logging. ...
Complement logging with Crash Reporting. ...
Generate a unique ID for each request to trace microservices. ...
Prepare each microservice for accepting and storing request IDs. ...
Create and implement your own logging patterns. ...
Use a logging framework.

38. what is @ControllerAdvise


@controllerAdvise is solution for global exception handler for multiple
exception handling in application.

39. Whats is composition in java ? and types


Composition : is relation ship between one or more objects
Has-A : Car - Engine
Is-A : Car - Vechilce - maruthi.

40.how to secure rest api request sensitive data?


Implement authentication and authorization. ...
Use SSL/TLS encryption. ...
Implement rate limiting. ...
Use auditing and logging. ...
Restrict access to sensitive data. ...
Monitor and alert on anomalous activity.

41. what are microservice design pattrens?


https://dzone.com/articles/design-patterns-for-microservices

1. Decomposition Patterns:
Decompose by Business Capability - split thes service by bussiness
like, sales, marketing,claims,billing etc
Decompose by Subdomain - Each subdomain will have a model, and the
scope of that model will be called the bounded context
Strangler Pattern - The Strangler pattern comes to the rescue. The
Strangler pattern is based on an analogy to a vine that strangles a tree
2. Integration Patterns:
API Gateway Pattern - each service has single point of contact for
multile services
Aggregator Pattern - multiple service response should aggregating
before sending to client
Client-Side UI Composition Pattern - client side should implement
supporate grids for multiple service response
3. Database Patterns
Database per Service - each serivce must be having different data base
Shared Database per Service - some time shared data base for one or
more services, exceptional case
Command Query Responsibility Segregation (CQRS) - fetching data is
defacult in one query, so spliting into command and query
Saga Pattern - failure service should have data consistency
4. Observability Patterns
Log Aggregation - We need a centralized logging service that aggregates
logs from each service instance. Users can search and analyze the logs.
Performance Metrics - A metrics service is required to gather
statistics about individual operations.
Distributed Tracing - Assigns each external request a unique external
request id.Passes the external request id to all services.
Health Check : /helth end point in springboot
5. Cross-Cutting Concern Patterns
External Configuration - Externalize all the configuration, including
endpoint URLs and credentials
Service Discovery Pattern - service register should create for all
produce service for dynamic ip
Circuit Breaker Pattern - calling external service, if it is down
stream cases. need to implement circuit breaker pattaren
Blue-Green Deployment Pattern - exisiting env green and latest version
env blue

42. whaat is ACID ? and each one can explain ?

A - Atomicity : The entire transaction takes it in one place.


C - Consistency : The data base must be consistent before and after
transaction.
I - Isolation : Multiple trasactions occurs independently without
interference.
D - Durablity : The changes of successfull transaction occurs even if the
system failure occurs.

43. what is idepontent ?


When using an idempotent method, the method can be called multiple times
without changing the result. For example, using GET, an API can retrieve a REST
resource. This has no effect on the resource and can be repeated over and over.

44. what is context switching ?


A context switching helps to share a single CPU across all processes to
complete its execution and store the system's tasks status. When the process
reloads in the system, the execution of the process starts at the same point where
there is conflicting

45. what is Service Registary in Microservice ?


A service registry is a database used to keep track of the available
instances of each microservice in an application.
The service registry needs to be updated each time a new service comes online
and whenever a service is taken offline or becomes unavailable

46. how many ways we can make thread safe singleton ?


Synchronized getInstance method()
static inner class and syncronized block

47. diff jdbc and JPA? and peroframnce ?


- jdbc - query need to change for different data bases
- jdbc - result set need iterate and assign to bean
- JPA - is orm query need not change any database
- JPA - mapping result to bean with entity class

JPA is 4x slower than JDBC when it comes to large-batch processing. Mapping


between database tables can be a bit challenging

48. Settings.xml maveen repository ?


users/.m2/config/setting.xml
49. Spring profile ? how to enable and where to mention ?
@Configuration
@Profile("master")
public class MasterConfiguration {
// @Bean definitions needed for a master
}

@Profile("!mock")
OutputPort realOutputPort(){
return new RealOutputPort();
}

50. war genrate POM.xml steps ?


<groupId>com.example.projects</groupId>
<artifactId>documentedproject</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Documented Project</name>
<url>http://example.com</url>

51.Stream collect() and what will happen if not providing collect(),max() methods
in filetr.
What happens when you terminate a stream with a filter? Nothing happens. It
just creates another stream, and this is not the functionality of a stream.
An Example:

Stream<String> intermediateStream = Stream.of("one", "two", "three")


.filter(s ->
s.length() > 3);
This intermediateStream doesn't do anything; it is just a Java variable of
type Stream<T>. There is no operation or result until a terminal operation is run
on it. For example:

intermediateStream.forEach(System.out::println); // this prints "three".

52. what is Join() method ?


Join method in Java allows one thread to wait until another thread completes
its execution

53. what is @enableautoconfigurstion do ?


@EnableAutoConfiguration annotation enables Spring Boot to auto-configure the
application context
it automatically creates and registers beans based on both the included jar
files in the classpath and the beans defined by us

54.where to change default port to new port in springboot?


1.in application.prop - > server.port=8081
2.SpringApplication app = new SpringApplication(CustomApplication.class);
app.setDefaultProperties(Collections
.singletonMap("server.port", "8083"));
app.run(args);

55.what is domain driven design in microservices?


Domain-driven design helps in designing a microservice-based architecture by
breaking the complex system into smaller, independent parts, comprehending their
functions, and figuring out how these parts relate to one another
56. how to handle 10millen records to inseart?
- concurance method - using excuter service -- each thread can split the rows and
inseart fats
- Azure Cosmos DB bulk executor library - each Thread split the task and store
faaster in db

57.what is Interceptor in spring ?


Interceptors are used in conjunction with Java EE managed classes to allow
developers to invoke interceptor methods on an associated target class, in
conjunction with method invocations or lifecycle events. Common uses of
interceptors are logging, auditing, and profiling.

@override preHandler();
@override postHandler();
@override afterCompoletion();

58.Different kind of Thread pooling ?


Single Thread Executor : A thread pool with only one thread. So all the
submitted tasks will be executed sequentially. Method :
Executors.newSingleThreadExecutor()

Cached Thread Pool : A thread pool that creates as many threads it needs to
execute the task in parrallel. The old available threads will be reused for the new
tasks. If a thread is not used during 60 seconds, it will be terminated and removed
from the pool. Method : Executors.newCachedThreadPool()

Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread
is not available for the task, the task is put in queue waiting for an other task
to ends. Method : Executors.newFixedThreadPool()

Scheduled Thread Pool : A thread pool made to schedule future task. Method :
Executors.newScheduledThreadPool()

Single Thread Scheduled Pool : A thread pool with only one thread to schedule
future task. Method : Executors.newSingleThreadScheduledExecutor()

59. how to ignore some endpoints like, GET mthods in JWT and microservices ?
@Configuration
@Profile("test")
public class ApplicationNoSecurity {

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.antMatchers("/**");
}
}

60. what is SpringJPA advantage ?


JPA data is represented by classes and objects rather than by tables and
records as in JDBC
JPA handles most of the complexity of JDBC-based database access and object-
relational mappings. On top of that, Spring Data JPA reduces the amount of
boilerplate code required by JPA
No need to write DDL/DML queries, instead we can map by using
XML/annotations.
JPQL is used and since it is platform-independent, we no need to depend on
any native SQL table. ...
Entity can be partially stored in one database like MySQL and the rest can be
in Graph database Management System.
Dynamic generation of queries is possible.

61.Which is better JPA query or native query?


JPQL provides a higher level of abstraction and can help simplify queries,
but may not always be able to fully utilize the power of SQL. Using native SQL
queries can provide more flexibility in terms of performance optimization and
complex queries

62. what is kafka rebalancing ?


It ensures that each consumer is assigned a fair share of partitions,
maintaining load balance and maximizing throughput. During rebalancing, Kafka
considers several factors, such as the number of partitions, the number of
consumers, and the consumer group's current state

63. what is kafaka partition and for one partion how many consumers ?
Parttion enables messges to be split in parllel across several brokers in the
cluster.
Kafka assigns the partitions of a topic to the consumers in a group so that
each partition is assigned to one consumer in the group. This ensures that records
are processed in parallel and nobody steps on other consumers'

64.what is kafka commits ?


It commits the offset, indicating that all the previous records from that
partition have been processed. So, if a consumer stops and comes back later, it
restarts from the last committed position
auto. commit = true and set auto.commit.interval.ms=2000

65. how to restrict kafka messages not dublicate ?


By configuring the Producer to be idempotent, each Producer is assigned a
unique Id (PID) and each message is given a monotonically increasing sequence
number. The broker tracks the PID + sequence number combination for each partition,
rejecting any duplicate write requests it receives.

67. diff bw Query, Native Query, Named query and Typed Query?
Query refers to JPQL/HQL query with syntax similar to SQL generally used to
execute DML statements(CRUD operations).
-----
In JPA, you can create a query using entityManager.createQuery(). You can
look into API for more detail.

In Hibernate, you use session.createQuery()"

NativeQuery:
-----------
Native query refers to actual sql queries (referring to actual database
objects). These queries are the sql statements which can be directly executed in
database using a database client.

JPA : entityManager.createNativeQuery() Hibernate (Non-JPA implementation):


session.createSQLQuery()

NamedQuery:
-----------
Similar to how the constant is defined. NamedQuery is the way you define your
query by giving it a name. You could define this in mapping file in hibernate or
also using annotations at entity level.
TypedQuery:
----------
TypedQuery gives you an option to mention the type of entity when you create
a query and therefore any operation thereafter does not need an explicit cast to
the intended type. Whereas the normal Query API does not return the exact type of
Object you expect and you need to cast.

69. What is stream main Components ?


tuples, data streams, operators, processing elements (PEs), and jobs.

70. what is fault tolerance in microservices ? Circuit Breaker ?


Fault tolerance is the ability of a system to continue functioning despite
failures or errors in some of its components.

When you have a number of dependent services, failure in one component might
have a wider impact on a number of components

Implementing the Circuit Breaker Pattern


Circuit breaker functionality uses the following three states:

1.Closed – In this state, all connection requests are allowed, and service
communication is intact. During normal processing, the circuit breaker is in a
closed state. However, if set failure thresholds are exceeded, the state changes to
“open.”
2.Open – In this state, all connection requests are blocked to allow the
recovering service to be flooded with requests.
3.Half-open – In this state, a small number of connections are allowed to
pass through at regular intervals to test the service’s availability. If the
requests are successful, then the circuit breaker assumes that the service issue
has been resolved and switches it to the closed state. If the requests are not
successful, then the circuit breaker assumes that the service issue still exists
and switches back to the open state.

71. is your application is having single connection pool? are mutilple connection
pool?
Some module have single connection pools, and we can implement mutilple
connection pool if having mutiple dabase using.

72. Fetch Splunk log Queries example ?


Soruce="secure.log" host="mailsecure_log" sourcetype="securelogsorce"
fail*AND Password
fail*AND Password 3256
host="mailsecure_log" earliest=15d latest=7d

516 957 1949


73. Find the highest salary from employee table ?

Map.Entry<String,Integer> finalResult = map.entrySet()


.stream()
.sorted(Comparator.comparing(entry -> -entry.getValue())) // minus make
it to do in desc order
.toList()
.get(0); // index start from 0 , if you want 2 highest get(1) ..like nth
highest.

74. which one is fatser for iterating java collection object ?


while(), forEach(), for() these methodas are faster then Iteration or
stream() api.
75. Find count of the employee based on department ?
Map<String, Long> employeeCountByDepartment =
list.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
TreeMap::new, Collectors.counting()));

76. remove/ find the dublicate elements from array integer ?


Integer[] arr = new Integer[]{8,8,7,6,7,3,2,1,3};
List<Integer> list = Arrays.asList(arr);
Set<Integer> set = new HashSet<>();
//list.stream().filter(e-> !set.add(e)).forEach(ex->System.out.println(ex));
// it find dublicate elements {8,7,3}
list.stream().distinct().forEach(ex->System.out.println(ex)); // distinct
elemnets {8,7,6,3,2,1}

// removing all dublicates

77. Spring boot main components ?


Spring Boot Starter : Spring Boot Starter is to combine a group of common or
related dependencies into single dependencies
Spring Boot AutoConfigurator: The main responsibility of Spring Boot
AutoConfigurator is to reduce the Spring Configuration
@SpringBootApplication =
@Configuration + @ComponentScan + @EnableAutoConfiration
Spring Boot CLI(Command Line Interface): to run and test Spring Boot
applications from command prompt (spring run HelloWorld.groovy)
Spring Boot Actuator: Providing Management EndPoints to Spring Boot
Applications and Metrics.https://localhost:8080/health

78. what are the Microservice components ?


Services: This is the heart of microservices, where your business logic
lives.

APIs: These provide a way for services to communicate with each other.

Databases: This is where your application data is stored.

Schedulers: These control when services run and how they interact.

Service Monitoring: This ensures that your microservices are running properly
and collect data for analysis.

Service discovery: A service registry that helps services locate and


communicate with each other

API gateway: An entry point for client requests that routes requests to the
appropriate microservices

Load Balancer: A component that distributes incoming requests to the


appropriate service instances.

Service Registry: A database of all available microservices, their endpoints,


and metadata.

Circuit Breaker:helps prevent cascading failures by interrupting


communication between services when one service is not responding.

Service Orchestration: A layer that coordinates communication and


interactions between microservices to ensure that they work together correctly.

Configuration Server: A centralized repository for storing configuration


information that is accessible to all microservices.

79. how to handle @Asnc request in springboot?


@Configuration
@AllArgsConstructor
public class AsyncConfiguration implements AsyncConfigurer{

private final GlobalAsyncExceptionHandler globalAsyncExceptionHandler;


// Async configuration
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor threadPoolExecutor=new
ThreadPoolTaskExecutor();
threadPoolExecutor.setCorePoolSize(10);
threadPoolExecutor.setMaxPoolSize(12);
threadPoolExecutor.setQueueCapacity(50);
threadPoolExecutor.setThreadNamePrefix("test-backend-async");
threadPoolExecutor.initialize();
return threadPoolExecutor;
}
//Async Exception configuration
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
{
return globalAsyncExceptionHandler;
}
}

You might also like