Monday, April 27, 2020

Java Technical Architect interview @ Tech Mahindra - Round - 1

Hi Friends,

In this post, I'm sharing Technical Architect interview round questions asked in Tech Mahindra.

Kindly also go through my other interview posts:







Question 1:

What are Spring boot actuator endpoints?

Answer 1:

Spring boot actuator is used to monitor and manage application usage in production environment without coding and configuration for any of them.

This monitoring and managing information is exposed via REST like endpoint URL's.

Actuator endpoints:

/env  : Returns list of properties of current environment.

/health : Returns application health information.

/beans : Returns a complete list of all the spring beans in the application.

/trace : Returns trace logs [By default last 100 HTTP requests]

/dump : It performs a thread dump.

/metrics : It shows several useful metrics information like JVM memory usage, CPU usage, open files and much more.

Note: These endpoints can be explicitly enabled/disabled.

If we need to list all endpoints in the browser:
Just run the application and from the browser, use localhost:8080/actuator. It will list 2 endpoints by default : info and health.

For other endpoints, we need to expose them manually.

Now, if we want to explore health endpoint, then just open localhost:8080/actuator/health URL and it will just display "status" : "UP"

We can enable or disable the endpoint from application.properties file:

management.endpoint.shutdown.enabled = true

By default , all the endpoints are enabled except shutdown endpoint.



Question 2:

What is the difference between map and flatmap in java 8?


Answer 2:

map() method is used to map an object or entry from stream to some other value.
flatMap() method on the other hand applies map() on the entries and then flatten the result.

e.g.:

Suppose we have a string array with entries:
String[] strArray = {"12", "46"};

And we have to find all permutations of these strings.
So output with map() method will be: [12, 21] , [46, 64]

While the output with flatMap() method will be : [12, 21, 46, 64]

Lets take another example:

List<Integer> evens = Arrays.asList(2,4,6,8);
List<Integer> odds = Arrays.asList(1,3,5,7);
List<Integer> primes = Arrays.asList(5,7,11,13);

List numbers = Stream.of(evens, odds, primes).flatMap(list-> list.stream()).collect(Collectors.toList());

System.out.println("List = "+numbers);

Note: this output is possible only with flatMap() method.




Question 3:

Explain Spring Data JPA versus Hibernate?


Answer 3:

JPA : Java Persistence API provides specification for creation, deletion, persistence and data management from java objects to relations [tables] in database.

Hibernate : There are various providers which implement JPA. Hibernate is one of them. So , we have other providers as well e.g.: Eclipse Link.

Spring Data JPA: This is another layer on top of JPA which spring provides to make coding easier.




Question 4:

When to use @Component and when to use @Bean?

Answer 4:

@Component is a class level annotation while @Bean is a method level annotation.

@Component is preferable for component scanning and automatic wiring.
Sometimes automatic configuratin is not an option. When? Let's imagine that we want to wire components from 3rd party libraries[where we don't have the source code ,so we can't annotate the class with @Component ], so automatic configuration is not possible.

So, in this case , we should use @Bean.

The @Bean annotation returns an object that spring should register as bean in application context/Spring IOC container. The body of the method bears the logic responsible for creating the instance.

Another difference is that:

@Component does not decouple the declaration of bean from the class definition whereas @Bean decouples the declaration of the bean from the class definition.


There are two ways to create beans:

One is to create a class with an annotation @Component. The other is to create a method and annotate it with @Bean.


@Bean requires the @Configuration annotation on the class in which @Bean is used. Whereas @Component doesn't require the class to be annotated with @Configuration.

Once we run the spring project, the class with @ComponentScan  annotation would scan every class with @Component on it and store the instance of this class to the IOC container.

Another thing , the @ComponentScan would do is , running the methods with @Bean on it and store the returned object to the IOC container as a bean.




Question 5:

Explain the use case with example where @Bean is more beneficial to use than @Component?

Answer 5:

Lets suppose, we want some specific implementation depending on some dynamic state. @Bean is perfect for that case.

@Bean
@Scope("prototype")
public Service anyService(){

    switch(state){
        case 1:
            return new Impl1();

        case 2:
            return new Impl2();

        case 3:
            return new Impl3();

        default:
            return new Impl();
 
    }
}


In the above case, only @Bean can be used , not the @Component.

Note:  We can use both @Component and @Configuration annotations in our same application/module.



Question 6:

Explain the difference between @Service and @Component in Spring.

Answer 6:

@Component is a generic for other stereotypes. 
So, we can replace @Component with @Service, @Repository or @Controller and nothing will change. But for better readability , we should use @Repository, @Service and @Controller.

They all inform spring that the class is involved in the DI context.

In order to configure spring so that it can provide us with the instances of the class we need , we are supposed to tell spring what objects are involved and how they are built. To do this, we can use XML configuration file or java annotations.

They also have semantic meaning:


  • @Controller : @Component belonging to presentation layer
  • @Service : @Component belonging to Service/Use case layer
  • @Repository : @Component belonging to Persistence layer 






That's all for this post.
Hope this post helps everybody in their interviews.

Thanks for reading !!

Wednesday, April 8, 2020

Microservice Interview - 4 : Circuit Breaker

Hi Friends,

In this blog post, I'm explaining the Circuit Breaker pattern that will cover all interview questions on this.


It is very important to prepare system in case of partial failure, especially for a microservice-based architectures, where there are many applications running in separate processes.

A single request from the client point of view might be forwarded through many different services and it is possible that one of thee services is down because of a failure, maintenance or just might be overloaded , which causes an extremely slow response to client requests coming into the system.

There are several best practices for dealing with failures and errors:


  • The first practice recommends that we should always set network connect and read timeouts to avoid waiting too long for the response.
  • The second approach is about limiting the number of accepted requests if a service fails or responses take too long. In this case, there is no sense in sending additional requests by the client.

The last two patterns are closely connected to each other. Here I'm thinking about the circuit breaker pattern and fallback.






Few points about the Circuit breaker diagram:

  • Initially the circuit is closed. Means the service is working fine , accepting requests and returning response.
  • When few requests get failed, circuit gets tripped and enter into Open state and doesn't allow any further request to go to that non-responding service.
  • In between, after some timeout , circuit breaker allows few requests to the non-responding service to check the status of that service. This state is called Half-open state as it allows only few requests to go further. If service responds well, then circuit gets into Closed state , else it will get into Open state again.



Circuit Breaker Pattern:

The major assumption of this approach relies on monitoring successful and failed requests. If too many requests fail or services take too long to respond, the configured circuit breaker is tripped and all further requests are rejected.


The most  popular implementation of Circuit Breaker pattern is available in Netflix Hystrix which is used by many java frameworks like Spring Cloud or Apache Camel.

Implementation of a circuit breaker with Spring Cloud Netflix is quite simple. 
In the main class, it can be enabled with one annotation:

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class Application{

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

}

And also need to add dependency :

In gradle:  Use :

compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-hystrix', version: '1.4.7.RELEASE'


For fallback mechanism, we can use FeignClient like:

Our service A is going to interact with service B , but circuit breaker is tripped and requests to service B are rejected.

So , we need to call any fallback method for providing the response.

A.java:


@FeignClient(name = "A",  url = " URL or endpoint of service B" , fallback = A.Fallback.class)
public interface A{

    @GetMapping(value = "/{id}?app_id={app_id}")
    ResponseEntity<String> getInfo(@PathVariable("id") String id);


    class Fallback implements A{

        @Override
        public ResponseEntity<String> getInfo(String id){

           // Send back any info.
        }

    }


}


A pictorial diagram is like:






That's all for this post.
Hope this post helps everyone in their interviews.
Thanks for reading!!




Saturday, April 4, 2020

Microservices Interview - 3 : CQRS

Hi Friends,

This post is all abut explanation of CQRS pattern in microservices.

CQRS :  Command Query Responsibility Segregation


This pattern says, we can use a different model to update information than the model we use to read information.


For some situations, this separation can be valuable, but for more systems, CQRS adds risky complexity.


Non-CQRS Model:

    



CQRS Model :
  





In this we have used different models for read (Query) and update (Command) operations.

By different models we mean different object models, probably running in different logical processes, perhaps on separate hardware.

A web example would see a user looking at a web page that's rendered using the Query model. If the user initiate a change, that change is routed to the separate command model for processing, the resulting change is communicated to the query model to render the updated state.

In this case, there is room for considerable variation here:

The in-memory models may share the same database, in which case, the database acts as the communication between the two models. However, they may also use separate databases, effectively making the query-side database into a real time Reporting database.

In this case, there needs to be some communication mechanism between the two models of their databases.

The two models might not be separate object models, it could be that the same objects have different interfaces for their command side and their query side.

CQRS naturally fits with some other architectural patterns:


  • As we move away from a single representation that we interact with via  CRUD, we can easily move to a task-based UI.
  • CQRS fits well with event-based programming models.  It's common to see CQRS system split into separate services communicating with event collaboration. This allows these services to take advantage of Event Sourcing.
  • Having separate models raises questions about how hard to keep those models consistent, which raises the likelihood of using eventual consistency.

It also solves a problem:
How to implement a query that retrieves data from multiple services in a microservice architecture?

Solution:

Define a view database that is a read-only replica which is designed to support that query.
The application keeps the replica up-to-date by subscribing to Domain events published by the service that own the data.








When to use CQRS:

In particular, CQRS should only be used on specific portions of a system (a Bounded Context in DDD lingo) and not the system as a whole.


BoundedContext:

Bounded Context is a central pattern in Domain-Driven Design.

Domain Driven Design deals with large models by dividing them into different bounded contexts and being explicit about their relationships.

e.g. of Bounded Context:






That's for this post.
Thanks for reading!!




Thursday, April 2, 2020

Spring Boot interview @ Sapient

Hi Friends,

Also go through my other interview posts:






Question 1:

What is the use case of Spring Boot?

Answer:

Spring Boot is used while creating microservices. As with increasing features in our applications, we need to create a separate microservice for each new feature and doing entire setup for this including adding all dependencies will  take time. So, in this scenario, Spring Boot is required.

In a monolithic application, we just do setup and dependency addition only once, so in monolithic application, we don't need spring boot.




Question 2:

What are the steps to use Spring-boot-starter-caching ?

Answer:

Steps for using spring-boot-starter-cache are following:

1). Add dependency: 

    <dependency>
        <groupId> org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache </artifactId>
    </dependency>

2). Add @EnableCaching annotation on main Spring Boot Application class.

The @EnableCaching triggers a post-processor that inspects every spring bean for the presence of caching annotations  on public methods. If such an annotation is found, a proxy is automatically created  to intercept the method call and handle the caching behavior accordingly.

The post-processor handles the @Cacheable, @CachePut and @CacheEvict annotations.

Spring boot automatically configures a suitable CacheManager to serve as a provider for the relevant cache.

3). Put @Cacheable and other annotations on methods.

e.g.:

public interface BookRepository{

    Book getByIsbn(String isbn);
}

Use our own implementation if we are not using Spring Data.

public class SimpleBookRepository implements BookRepository{

    @Override
    @Cacheable("books")
    public Book getByIsbn(String isbn){

        return new Book(isbn);
    }

}




Question 3:

What happens when we call SpringApplication.run() method in main class of SpringBoot application?

Answer:

Syntax of the class containing main method looks like code below:

@SpringBootApplication
public class StudentApplication{

    public static void main(String[] args){

        SpringApplication.run(StudentAppplication.class, args);
    }
}

When we run this class as a java application, then our application gets started.

SpringApplication.run() is a static method and it returns an object of ConfigurableApplicationContext.

ConfiguravleApplicationContext ctx = SpringApplication.run(StudentApplication.class, args);

Thus, Spring container gets started once run() method gets called.

Spring container once started is responsible for:


  • Creating all objects: This is done by @ComponentScan. Remember @SpringBootApplication is a combination of @ComponentScan + @Configuration + @EnableAutoConfiguration
  • Dependency injection
  • Managing the lifecycle of all beans
Steps executed under run() method are as follows:

  • Application Context is started.
  • Using application context, auto discovery occurs: @ComponentScan
  • All default configurations are setup.
  • An embedded servlet container is started e.g. Tomcat. No need to setup a separate web server. Note: Embedded servlet container is launched  only if the web is mentioned in a dependency.





Question 4:

What are Spring Boot Actuator endpoints?

Answer:

Spring Boot Actuator is used to monitor and manage application usages in production environment without coding and configuration for any of them.


This monitoring and managing information is exposed via REST like endpoint URL's.

Actuator Endpoints:

/env : Returns list of properties in current environment

/health : Returns application health information.

/beans : Returns a complete list of all the Spring beans in the application.

/trace : Returns trace logs [By default the last 100 HTTP requests]

/dump : It performs a thread dump

/metrics : It shows several useful metrics information like JVM memory used, CPU usage , open files and much more.

Note: These endpoints can be explicitly enabled/disabled.
 
If we need to list all endpoints in the browser:
Just run the application and from browser , use localhost:8080/actuator. It will list 2 endpoints by default : info and health

For other endpoints, we need to expose them manually.

Now, if we want to explore health endpoint, then just open localhost:8080/actuator/health URL and it will just display "status" : "UP"

We can enable or disable the endpoint from application.properties file:

management.endpoint.shutdown.enabled = true

By default all the endpoints are enabled except shutdown endpoint.




Question 5:

By default on which port Spring Boot Actuator runs?

Answer:

On port 8080

We can override that setting by adding application.properties file.



Question 6:

Difference between Spring 2 and Spring 5?

Answer:

Below are the differences between Spring 2 and Spring 5 versions:


  • JDK Baseline update
  • Core framework revision
  • Reactive programming model
  • Core Container updates
  • Testing improvements



Question 7:

What is the difference between @SpringBootApplication and @EnableAutoConfiguration?

Answer:

Following are the differences between @SpringBootApplication and @EnableAutoConfiguration:

Availability : SpringBootApplication was introduced in version 1.2 ,  While EnableAutoConfiguration was introduced in version 1.0

Purpose : @EnableAutoConfiguration enables auto configuration feature of Spring Boot application  which automatically configures things if certain classes are present in classpath e.g. : it can configure Thymeleaf  TemplateResolver and ViewResolver if Thymeleaf is present in the classpath.

On the other hand , @SpringBootApplication does three things.

  • It allows us to run the main class as a jar with an embedded container [Web server Tomcat]. 
  • It enables java configuration.
  • It enables component scanning. 




That's all from this interview.
Hope this post helps everybody in their interviews.
Thanks for reading!!

CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...