- Explain Singleton Design Pattern?
Java Singleton Pattern is one of
the Gangs of Four Design patterns and comes in the Creational
Design Pattern category. From the definition, it seems to be a
straightforward design pattern, but when it comes to implementation, it comes
with a lot of concerns.
Singleton Pattern
Principles
- Singleton pattern restricts
the instantiation of a class and ensures that only one instance of the
class exists in the Java Virtual Machine.
- The singleton class must
provide a global access point to get the instance of the class.
- Singleton pattern is used
for logging,
drivers objects, caching, and thread pool.
- Singleton design pattern is
also used in other design patterns like Abstract
Factory, Builder, Prototype, Facade,
etc.
- Singleton design pattern is
used in core Java classes also (for example, java.lang.Runtime, java.awt.Desktop).
Java Singleton
Pattern Implementation
To implement a singleton pattern, we
have different approaches, but all of them have the following common concepts.
- Private constructor to
restrict instantiation of the class from other classes.
- Private static variable of
the same class that is the only instance of the class.
- Public static method that
returns the instance of the class, this is the global access point for the
outer world to get the instance of the singleton class.
2. what are the scope of spring bean?
There are five types of spring
bean scopes:
- singleton - only one instance of
the spring bean will be created for the spring container. This is the
default spring bean scope. While using this scope, make sure bean doesn’t
have shared instance variables otherwise it might lead to data
inconsistency issues.
- prototype – A new instance will
be created every time the bean is requested from the spring container.
- request – This is same as
prototype scope, however it’s meant to be used for web applications. A new
instance of the bean will be created for each HTTP request.
- session – A new bean will be
created for each HTTP session by the container.
- global-session – This is used to
create global session beans for Portlet applications.
- Which
Annotations are used in Spring & Spring Boot?
Spring Boot Annotations like
- @Bean - The @Bean annotations
are used at the method level and indicate that a method produces a bean
that is to be managed by the Spring container
- @Service- It is used at the class
level. It shows that the annotated class is a service class, such as
business basic logic, and call external APIs.
- @Repository - It is a Data Access Object
(DAO) that accesses the database directly. It indicates that the annotated
class is a repository.
- @Configuration - It is used as a source of
bean definitions. It is a class-level annotation, The configuration annotation
represents the class having one or more @Bean methods. The spring
container could go ahead and generate the Spring Beans to be used.
- @Controller - The annotation is used to
indicate that the class is a web request handler. It is often used to
present web pages. It is most commonly used with @RequestMapping
annotation.
- @RequestMapping - RequestMapping is used to
map the HTTP request. It is used with the class as well as the method. It
has many other optional elements like consumes, name, method, request,
path, etc.
- @Autowired - This annotation is used to
auto-wire spring bean on setter methods, constructor and instance
variable. It injects object dependency implicitly. When we use this
annotation, the spring container auto-wires the bean by its matching data
type. The
Autowired annotation is used to inject the dependency in the bean. The
Autowired provides more control to the developers over where the Autowire
should be used.
- @Component - It is a class-level
annotation that turns the class into Spring bean at the auto-scan time. The component annotation can
automatically detect custom beans. It represents that the framework could
autodetect these classes for dependency injection
- @SpringBootApplication - It consists of
@Configuration, @ComponentScan, and @EnabeAutoConfiguration. The class
annotated with @SpringBootApplication is kept in the base package. This
annotation does the component scan. However, only the sub-packages are
scanned. The SpringBoot Application mark a
configuration class that declares Bean methods, either one or more than
that. The Spring Boot Application contains-
- Auto-configuration
- Spring
Boot Configuration
- Component
Scan
1 @EnableAutoConfiguration
It is placed on the main application class. Based
on classpath settings, other beans, and various property settings, this
annotation instructs SpringBoot to start adding beans.
The Enable Auto Configuration allows the spring
boot to auto-figure the application context. The applications are auto figured
basis the added jar dependencies.
11@ComponetScan
It is used to scan a package of beans. It is used
with the annotation @Configuration to allow Spring to know the packages to be
scanned for annotated components. This annotation is also used to specify base
packages.
12@Required
This annotation is applied to bean setter methods.
It indicates that the required property must be filled at the configuration
time in the affected bean, or else it throws an exception:
BeanInitializationException.
13. @Qualifier
It is used along with @Autowired annotation. It is
used when more control is required over the dependency injection process.
Individual constructor arguments or method parameters can be specified by using
this annotation. Confusion arises when more than one bean of the same type is
created, and only one of them is to be wired with a property, @Qualifier is
used to get rid of the confusion.
@Lazy
It is used in the component class. At startup, all
auto-wired dependencies are created and configured. But a @Lazy annotation can
be created if a bean is to be initialized lazily. This means that only if it is
requested for a bean will be created. It can also be used on @Configuartion
classes. It’s an indication that all @Bean methods within that @Configuration
should be lazily initialized.
- What
is method overriding?
If
subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.
Usage of Java Method Overriding
- Method
overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
- Method
overriding is used for runtime polymorphism
Rules for Java Method Overriding
- The
method must have the same name as in the parent class
- The
method must have the same parameter as in the parent class.
- There
must be an IS-A relationship (inheritance).
- What
are the Java 8 features
Java 8 provides following features
for Java Programming:
- Lambda expressions,
- Method references,
- Functional interfaces,
- Stream API,
- Default methods,
- Base64 Encode Decode,
- Static methods in interface,
- Optional class,
- Collectors class,
- ForEach() method,
- Nashorn JavaScript Engine,
- Parallel Array Sorting,
- Type and Repating Annotations,
- IO Enhancements,
- Concurrency Enhancements,
- JDBC Enhancements etc.
- Difference
between functional interface and abstract class
https://teachtojava.blogspot.com/2016/08/difference-between-abstract-class-and.html
- Difference
between filter & map
Both of these methods are present in Stream API and
which is used to perform sequential and parallel operations. Apart from this
point, these two methods are intermediate operations and return a
Stream as a result.
Note: map() and
filter() methods can be invoked on a single stream. There is no
restriction to use the only operation at a time.
he
following are the differences and similarities of map() and filter() methods.
Stream map()
A) map() operation is part of Stream API.
B) map() is an Intermediate Operation.
C) map() method takes as an argument
Function functional interface and Function implementation will return the same
as input or different type.
D) map() returns a Stream<T>
E)
map() method returned Stream preserves the order of how they appear in the
original list or Stream.
F) All values in the stream must be
traversed through the logic of the Function function interface. (map() logic)
G) This will be returning a value which is
mandatory. If not returning will result in a compile-time error.
H) map() method will always transform the current
value or object into another type or same type. If we do not want to pass the
value to the next step then we need to return a null value from the map()
method.
Stream filter()
A) filter() operation is part of Stream
API.
B) filter() is an Intermediate Operation.
C) filter() method takes as an argument
Predicate functional interface and Predicate tells true or false about the
predicate condition.
D) filter() returns a Stream<T>.
E) filter() method returned Stream
preserves the order how they appear in the original list or Stream.
F) All values in the stream must be
traversed through the logic of Predicate function interface. (filter() logic)
G) This will also be returning a value that
is mandatory. If not returning will result in a compile-time error.
H) filter() method passes the values to the next
step if the filter condition is true. Otherwise, the current object will be
skipped from processing in the next step.
- Difference
between filter and flat filter
The difference is that the map operation produces
one output value for each input value, whereas the flatMap operation produces
an arbitrary number (zero or more) values for each input value.
- Examples
for functional interface?
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
Some Built-in Java Functional Interfaces
Since Java SE
1.8 onwards, there are many interfaces that are converted into functional
interface. All these interfaces are annotated with @FunctionalInterface. These
interfaces are as follows –
·
Runnable –> This interface only contains the run() method.
·
Comparable –> This interface only contains the compareTo() method.
·
ActionListener –> This interface only contains the actionPerformed()
method.
·
Callable –> This interface only contains the call() method.
Java SE 8 included four main kinds of functional
interfaces which can be applied in multiple situations. These
are:
1.
Consumer
2.
Predicate
3.
Function
4. Supplier
Amidst the previous four interfaces, the first
three interfaces,i.e., Consumer, Predicate, and Function, likewise have
additions that are provided beneath –
1.
Consumer -> Bi-Consumer
2.
Predicate -> Bi-Predicate
3.
Function -> Bi-Function, Unary Operator, Binary Operator
- Difference
between primary key and unique key?
The primary key is
accepted as a unique or sole identifier for every record in the table. In the case of a primary key, we cannot save NULL values. In the case
of a unique key, we can save a null value, however, only one NULL value is
supported.
Comparison Chart:
Parameter |
PRIMARY
KEY |
UNIQUE
KEY |
Basic |
Used to serve as a unique
identifier for each row in a table. |
Uniquely determines a row which
isn’t primary key. |
NULL value acceptance |
Cannot accept NULL values. |
Can accepts NULL values. |
Number of keys that can be
defined in the table |
Only one primary key |
More than one unique key |
Index |
Creates clustered index |
Creates non-clustered index |
Auto Increment |
A Primary key supports auto
increment value. |
A unique key does not supports
auto increment value. |
Modification |
We cannot change or delete
values stored in primary keys. |
We can change unique key
values. |
@RequestParam annotation fetch the value of request parameter in the form of passing request parameter with url but @PathVariable annotation fetching value of the parameter in the form request URI template with some placeholder.
What is the use of @RequestBody Annotation in Spring and Spring Boot?
The @RequestBody annotation is
responsible for binding the HTTPRequest body to the body of the web request.
Depending on the content type of the request, the body of the request is given
through a HttpMessageConverter, which resolves the
method argument.
We can also use
the @Valid annotation to automatically validate the input.
In brief, the @RequestBody annotation is
responsible for retrieving the request body and automatically converting it to
the Java object.
- What
is lambda expression
Lambdas are similar to methods, but they do not need a name
and can be implemented outside of classes. As a result, they open the
possibility for fully functional programs and pave the way for more functional
support from Java in the future.
The syntax of a basic lambda expression is:
parameter -> expression
- What
is default method in java?
Before Java 8, interfaces could have only abstract methods.
The implementation of these methods has to be provided in a separate class. So,
if a new method is to be added in an interface, then its implementation code
has to be provided in the class implementing the same interface. To overcome
this issue, Java 8 has introduced the concept of default methods which allow
the interfaces to have methods with implementation without affecting the
classes that implement the interface.
The default methods were introduced to provide backward
compatibility so that existing interfaces can use the lambda expressions
without implementing the methods in the implementation class. Default methods
are also known as defender methods or virtual
extension methods.
Default Methods and Multiple Inheritance
In case both the implemented interfaces contain default methods with same
method signature, the implementing class should explicitly specify which
default method is to be used or it should override the default method.
- Comparable Interface is actually from java.lang package.
- It will have a method compareTo(Object obj)to sort objects
- Comparator Interface is actually from java.util package.
- It will have a method compare(Object obj1, Object obj2)to sort objects
- Difference
between monolithic & microservices
Monolithic vs Microservices architecture
In order to understand microservices, we need to
understand what are monolithic applications and what led us to move from
monolithic applications to microservices in recent times.
Monolithic applications
If all the functionalities of a project exist in a single codebase, then that
application is known as a monolithic application. We all must have designed a
monolithic application in our lives in which we were given a problem statement
and were asked to design a system with various functionalities. We design our
application in various layers like presentation, service, and persistence and
then deploy that codebase as a single jar/war file. This is nothing but a
monolithic application, where “mono” represents the single codebase
containing all the required functionalities.
Disadvantages of Monolithic applications:
·
It becomes too large with time and hence, difficult to manage.
·
We need to redeploy the whole application, even for a small change.
·
As the size of the application increases, its start-up and
deployment time also increases.
·
For any new developer joining the project, it is very difficult
to understand the logic of a large Monolithic application even if his
responsibility is related to a single functionality.
·
Even if a single part of the application is facing a large
load/traffic, we need to deploy the instances of the entire application in
multiple servers. It is very inefficient and takes up more resources
unnecessarily. Hence, horizontal scaling is not feasible in monolithic
applications.
·
It is very difficult to adopt any new technology which is well
suited for a particular functionality as it affects the entire application,
both in terms of time and cost.
·
It is not very reliable, as a single bug in any module can bring
down the entire monolithic application.
Advantages of monolithic applications:
·
Simple to develop relative to microservices, where skilled
developers are required in order to identify and develop the services.
·
Easier to deploy as only a single jar/war file is deployed.
·
Relatively easier and simple to develop in comparison to
microservices architecture.
·
The problems of network latency and security are relatively less
in comparison to microservices architecture.
·
Developers need not learn different applications, they can keep
their focus on one application.
Microservices
It is an architectural development style in which the application is made up of
smaller services that handle a small portion of the functionality and data by
communicating with each other directly using lightweight protocols like HTTP.
According to Sam Newman, “Microservices are the small services that work
together.”
The Microservice architecture has a significant impact on
the relationship between the application and the database. Instead of sharing a
single database with other microservices, each microservice has its own
database. It often results in duplication of some data, but having a database
per microservice is essential if you want to benefit from this architecture, as
it ensures loose coupling. Another advantage of having a separate database per
microservice is that each microservice can use the type of database best suited
for its needs. Each service offers a secure module boundary so that different
services can be written in different programming languages. There are many
patterns involved in microservice architecture like service discovery &
registry, caching, API gateway & communication, observability, security,
etc.
Principles of microservices:
·
Single responsibility: It
is one of the principles defined as a part of the SOLID design pattern. It
states that a single unit, either a class, a method, or a microservice should
have one and only one responsibility. Each microservice must have a single
responsibility and provide a single functionality. You can also say that: the
number of microservices you should develop is equal to the number of
functionalities you require. The database is also decentralized and, generally,
each microservice has its own database.
·
Built around business capabilities: In
today’s world, where so many technologies exist, there is always a technology
that is best suited for implementing a particular functionality. But in
monolithic applications, it was a major drawback, as we can’t use different
technology for each functionality and hence, need to compromise in particular
areas. A microservice shall never restrict itself from adopting an appropriate
technology stack or backend database storage that is most suitable for solving
the business purpose, i.e., each microservice can use different technology
based on business requirements.
·
Design for failure: Microservices
must be designed with failure cases in mind. Microservices must exploit the
advantage of this architecture and going down one microservice should not
affect the whole system, other functionalities must remain accessible to the
user. But this was not the case in the Monolithic applications, where the
failure of one module leads to the downfall of the whole application.
Service-oriented architecture (SOA) vs Microservices architecture:
Steve Jones, MDM at Capgemini once said, “Microservices
is SOA, for those who know what SOA is”. So, those who know about SOA, most
think that they are the same, or the difference is not much clearer in their
mind. We can’t blame them also, if we talk about a cake and a pastry, we will
find more similarities than differences. So let’s try to understand the
differences between the two.
SOA evolved in order to deal with the problems in monolithic architecture and
became popular in the early 2000s. In SOA, the large application is split up
into multiple smaller services that are deployed independently. These services
don’t communicate with each other directly. There used to be an Enterprise
Service Bus (ESB, a middleware or server with the help of services using
different protocols or message standards that can communicate with each other
easily) where these services expose themselves and communicate with each other
through it. Also, there was no guideline to have an independent database for
each service.
Microservices architecture is an evolution of SOA. People
also consider SOA as a superset of microservices. In simple terms,
microservices is a fine-grained SOA. Here, the microservices communicate with
each other directly and there is no central dependency for communication such
as ESB in SOA. Also, there is a guideline to have a separate database for each
microservice. The fundamental idea of the evolution of microservices from SOA
is to reduce the dependency between the services and make them loosely coupled
with the above-mentioned guidelines.
Advantages of microservices:
·
It is easy to manage as it is relatively smaller.
·
If there’s any update in one of the microservices, then we need
to redeploy only that microservice.
·
Microservices are self-contained and, hence, deployed
independently. Their start-up and deployment times are relatively less.
·
It is very easy for a new developer to onboard the project as he
needs to understand only a particular microservice providing the functionality
he will be working on and not the whole system.
·
If a particular microservice is facing a large load because of
the users using that functionality in excess, then we need to scale out that
microservice only. Hence, the microservices architecture supports horizontal
scaling.
·
Each microservice can use different technology based on the
business requirements.
·
If a particular microservice goes down due to some bug, then it
doesn’t affect other microservices and the whole system remains intact and
continues providing other functionalities to the users.
Disadvantages of microservices:
·
Being a distributed system, it is much more complex than
monolithic applications. Its complexity increases with the increase in a number
of microservices.
·
Skilled developers are required to work with microservices
architecture, which can identify the microservices and manage their
inter-communications.
·
Independent deployment of microservices is complicated.
·
Microservices are costly in terms of network usage as they need
to interact with each other and all these remote calls result in network
latency.
·
Microservices are less secure relative to monolithic applications
due to the inter-services communication over the network.
·
Debugging is difficult as the control flows over many
microservices and to point out why and where exactly the error occurred is a
difficult task.
What Is Load
Balancing in microservice architecture?
Load balancing is the process of distributing traffic among different
instances of the same application.
To create a fault-tolerant system, it's common to run multiple instances
of each application. Thus, whenever one service needs to communicate with
another, it needs to pick a particular instance to send its request.
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)
what is use of profile in spring boot
Enterprise
application development is complex. You have multiple environments
- Dev
- QA
- Stage
- Production
You want to have
different application configuration in each of the environments.
Profiles help to
have different application configuration for different environments.
Spring and Spring
Boot provide features where you can specify
- What is the configuration
for various environments in different profiles?
- Set the active profile for a
specific environment.
Spring Boot would
pick up the application configuration based on the active profile that is set
in a specific environment.
- Is
it allow multiple application.properties files or not in spring boot
application
Spring Boot supports different properties
based on the Spring active profile. For example, we can keep two separate files for development
and production to run the Spring Boot application.
- What
is use of Optional
Every Java Programmer is familiar with NullPointerException.
It can crash your code. And it is very hard to avoid it without using too many
null checks. So, to overcome this, Java 8 has introduced a new class
Optional in java.util package. It can help in writing a neat code
without using too many null checks. By using Optional, we can specify alternate
values to return or alternate code to run. This makes the code more readable
because the facts which were hidden are now visible to the developer.