Saturday, December 28, 2019

Java 1.8 interview Questions

Name a few recent features introduced in Java 8.

Below are the most recent features which is introduced in Java 8:

  • Lambda Expressions: It is a Java function that you can share or refer to as an object.
  • Method interference: It uses function as a criterion to implement a method.
  • Functional Interference: Every functional interference is associated with a single abstract method which is known as the functional method.
  • Default Method: It is useful in implementing methods in the interfaces that help enable the ‘interface evolution’ potential.
  • Date Time API: It is an improved yet inspired version of java time APIs to deal with the drawbacks of the last version.
  • Stream API is referred to as the abstract layer, which helps to pipeline the processing data.
  • Optional: The wrapper class is useful in checking the null values and processing the further data.
  • JavaScript and Nashorn Engine: It is the improved version of the JavaScript Engine, which is useful in enabling its functionality in Java, replacing Rhino.

In which programming paradigm Java 8 falls?

  • Object-oriented programming language.
  • Functional programming language.
  • Procedural programming language.
  • Logic programming language 

What are the significant advantages of Java 8?

  • Compact, readable, and reusable code.
  • Less boilerplate code.
  • Parallel operations and execution.
  • Can be ported across operating systems.
  • High stability.
  • Stable environment.
  • Adequate support

What is MetaSpace? How does it differ from PermGen?

PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory type before Java 8. PremGen is fixed in size and cannot be dynamically resized. It was a contiguous Java Heap Memory.

MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a contiguous Heap Memory and hence can be grown dynamically which helps to overcome the size constraints. This improves the garbage collection, auto-tuning, and de-allocation of metadata.

What is the use of the @FunctionalInterface annotation?

This annotation is used in functional interfaces to add more readability to the code as an informative aspect. However, it does not affect the runtime or the semantics of the code.

What is the meaning of functional interfaces in Java 8?

Functional interfaces in Java 8 are interfaces having a single abstract method.

Following are the three types of methods that can be present:

  • The static method
  • The default method
  • The overridden class method

What is the meaning of method reference in Java 8?

Method references are used in Java 8 to refer to methods of functional interfaces. It can be considered as a short-code version of using a lambda expression.

The following is the expression for a method reference:

Class::methodname

For e.g.: 

Integer::parseInt(str) \\ method reference

str -> Integer.ParseInt(str); \\ equivalent lambda

What is the lambda expression in Java and How does a lambda expression relate to a functional interface?

Lambda expression is a type of function without a name. It may or may not have results and parameters. It is known as an anonymous function as it does not have type information by itself. It is executed on-demand. It is beneficial in iterating, filtering, and extracting data from a collection.

As lambda expressions are similar to anonymous functions, they can only be applied to the single abstract method of Functional Interface. It will infer the return type, type, and several arguments from the signature of the abstract method of functional interface.

Describe the syntax of a lambda expression.

Lambda expressions can be divided into three parts as shown in the below syntax:

//Lambda expression: (int a, int b) -> { System.out.println(a+b); return a+b;}

  1. Arguments: A lambda expression can have zero or more arguments at any point in time.
  2. Array token: It is used to point to the body of the expression.
  3. Body: The body consists of expressions and statements. Braces are not required if it has onl a single statement.

 What are the types and common ways to use lambda expressions?

A lambda expression does not have any specific type by itself. A lambda expression receives type once it is assigned to a functional interface. That same lambda expression can be assigned to different functional interface types and can have a different type.

For eg consider expression s -> s.isEmpty() :

Predicate<String> stringPredicate = s -> s.isEmpty(); 
Predicate<List> listPredicate = s -> s.isEmpty();
Function<String, Boolean> func = s -> s.isEmpty();
Consumer<String> stringConsumer = s -> s.isEmpty();

Common ways to use the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty();
Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty())
Returning it from a function —> return s -> s.isEmpty()
Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()
        

Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional interface. E.g:

interface Parent {

public int parentMethod();

}

@FunctionalInterface // This cannot be FunctionalInterface

interface Child extends Parent {

public int childMethod();

// It will also extend the abstract method of the Parent Interface

// Hence it will have more than one abstract method

// And will give a compiler error

}

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal methods. For eg:

interface Parent {

public void parentMethod(){

System.out.println("Hello");

}

}

@FunctionalInterface

interface Child extends Parent {

public int childMethod();

}

What is the default method, and why is it required?

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. In case a new abstract method is added to the interface, all classes implementing the interface will break and will have to implement the new method. With default methods, there will not be any impact on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.

@FunctionalInterface // Annotation is optional

public interface Foo() {

// Default Method - Optional can be 0 or more

public default String HelloWorld() {

return "Hello World";

}

// Single Abstract Method

public void bar();

}

What are static methods in Interfaces?

Static methods, which contains method implementation is owned by the interface and is invoked using the name of the interface, it is suitable for defining the utility methods and cannot be overridden.

 

 

What are some standard Java pre-defined functional interfaces?

Some of the famous pre-defined functional interfaces from previous Java versions are Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function doc for other predefined functional interfaces and its description introduced in Java 8.

Runnable: use to execute the instances of a class over another thread with no arguments and no return value. 

Callable: use to execute the instances of a class over another thread with no arguments and it either returns a value or throws an exception.

Comparator: use to sort different objects in a user-defined order

Comparable: use to sort objects in the natural sort order.

What are the various categories of pre-defined function interfaces?

Function<T,R>: Represents a function that takes an argument of type T and produces a result of type R

Ex: Function<Integer, String> intToString = num -> "Number: " + num; System.out.println(intToString.apply(10)); // "Number: 10"

Predicate<R>: To perform a test and return a Boolean value.

Ex: Predicate<String> isNotEmpty = str -> !str.isEmpty(); System.out.println(isNotEmpty.test("Hello")); // true System.out.println(isNotEmpty.test("")); // false

Consumer: Represents an operation that accepts a single input argument and returns no result.

Ex: Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase()); printUpperCase.accept("hello"); // "HELLO"

Supplier: Represents a supplier of results. It provides a result of type T and does not take any arguments.

Ex: Supplier<String> getGreeting = () -> "Hello, World!"; System.out.println(getGreeting.get()); // "Hello, World!"

Operator: Perform a reduction type operation that accepts the same input types

Summary

  • Predicate<T>: Tests a condition.
  • Function<T, R>: Transforms an input to an output.
  • Consumer<T>: Accepts an input and performs an action without returning a result.
  • Supplier<T>: Provides a result without any input.
  • BinaryOperator<T>: Operates on two operands of the same type.
  • UnaryOperator<T>: Operates on a single operand of the same type.

What are the advantages of using the Optional class?

The optional keyword is used in Java 8 to avoid the occurrence of the NullPointerException.

It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks, which results in better, readable, and robust code It acts as a wrapper around the object and returns an object instead of a value, which can be used to avoid run-time NullPointerExceptions.

What are Java 8 streams?

A stream is an abstraction to express data processing queries in a declarative way. 

Stream pipelining is a concept that is implemented in Java 8 so that users can chain more than one operation at a time. This works on the principle of splitting the operation into two categories:

  • Intermediate operations: Return the instance of the stream when running
  • Terminal operations: Used to terminate the operation and return the final value

When is an ideal situation to use the Stream API in Java 8?

The Stream API in Java 8 can be effectively used if the Java project calls for the following operations:

  1. Perform database operations
  2. Execute operations lazily
  3. Write functional-style programming
  4. Perform parallel processing
  5. Use pipeline operations
  6. Use internal iteration

 What are the main components of a Stream?

Components of the stream are:

  • A data source
  • Set of Intermediate Operations to process the data source
  • Single Terminal Operation that produces the result 

 What are the sources of data objects a Stream can process?

A Stream can process the following data:

  • A collection of an Array.
  • An I/O channel or an input device.
  • A reactive source (e.g., comments in social media or tweets/re-tweets) 
  • A stream generator function or a static factory.

What are Intermediate and Terminal operations?

Intermediate Operations:

  • Process the stream elements.
  • Typically transforms a stream into another stream.
  • Are lazy, i.e., not executed till a terminal operation is invoked.
  • Does internal iteration of all source elements.
  • Any number of operations can be chained in the processing pipeline.
  • Operations are applied as per the defined order.
  • Intermediate operations are mostly lambda functions.

Terminal Operations:

  • Kick-starts the Stream pipeline.
  • used to collect the processed Stream data.

int count = Stream.of(1, 2, 3, 4, 5)

.filter(i -> i <4) // Intermediate Operation filter

.count(); // Terminal Operation count 

What are the most commonly used Intermediate operations?

Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns elements that are satisfying the supplied condition by the predicate.

map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by applying the supplied mapper function.= sorted() - Sorts the input elements and then passes them to the next stage.

distinct() - Only pass on elements to the next stage, not passed yet.

limit(long maxsize) - Limit the stream size to maxsize.

skip(long start) - Skip the initial elements till the start.

peek(Consumer) - Apply a consumer without modification to the stream.

flatMap(mapper) - Transform each element to a stream of its constituent elements and flatten all the streams into a single stream.

What is the stateful intermediate operation? Give some examples of stateful intermediate operations.

To complete some of the intermediate operations, some state is to be maintained, and such intermediate operations are called stateful intermediate operations. Parallel execution of these types of operations is complex.

For Eg: sorted() , distinct() , limit() , skip() etc. 

Sending data elements to further steps in the pipeline stops till all the data is sorted for sorted() and stream data elements are stored in temporary data structures.

What is the most common type of Terminal operations?

  • collect() - Collects single result from all elements of the stream sequence.
  • reduce() - Produces a single result from all elements of the stream sequence
    • count() - Returns the number of elements on the stream.
    • min() - Returns the min element from the stream.
    • max() - Returns the max element from the stream.
  • Search/Query operations
    • anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
    • Takes a Predicate as input for the match condition.
    • Stream processing will be stopped, as and when the result can be determined.
  • Iterative operations
    • forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
    • forEachOrdered() - It is helpful to maintain order in parallel streams.

What is the difference between findFirst() and findAny()?

findFirst()

findAny()

Returns the first element in the Stream

Return any element from the Stream

Deterministic in nature

Non-deterministic in nature

How are Collections different from Stream?

Collections are the source for the Stream. Java 8 collection API is enhanced with the default methods returning Stream<T> from the collections.

Collections

Streams

Data structure holds all the data elements

No data is stored. Have the capacity to process an infinite number of elements on demand

External Iteration

Internal Iteration

Can be processed any number of times

Traversed only once

Elements are easy to access

No direct way of accessing specific elements

Is a data store

Is an API to process the data

What are Map and FlatMap stream operations?

Map and FlatMap are regarded as the stream and intermediate stream operations which accepts a function. It also helps in applying the given function to the rest of the elements.

What were the issues that were fixed with the new Date and Time API of Java 8?

With the older versions of Java, java.util.The date was mutable. This means it has absolutely no thread safety.

Also, java.text.SimpleDateFormat was not thread-safe in the older versions. The older Date and Time API was difficult to understand for programmers in terms of readability too.

What is the feature of the new Date and Time API in Java 8?

  • Immutable classes and Thread-safe 
  • Timezone support
  • Fluent methods for object creation and arithmetic
  • Addresses I18N issue for earlier APIs
  • Influenced by popular joda-time package
  • All packages are based on the ISO-8601 calendar system

What are the important packages for the new Data and Time API?

  • java.time
    • dates 
    • times 
    • Instants 
    • durations 
    • time-zones 
    • periods
  • Java.time.format
  • Java.time.temporal
  • java.time.zone

Explain with example, LocalDate, LocalTime, and LocalDateTime APIs.

LocalDate

  • Date with no time component
  • Default format - yyyy-MM-dd (2020-02-20)
  • LocalDate today = LocalDate.now();  // gives today’s date
  • LocalDate aDate = LocalDate.of(2011, 12, 30); //(year, month, date)

LocalTime

  • Time with no date with nanosecond precision
  • Default format - hh:mm:ss:zzz (12:06:03.015) nanosecond is optional
  • LocalTime now = LocalTime.now();  // gives time now
  • LocalTime aTime2 = LocalTime.of(18, 20, 30); // (hours, min, sec)

LocalDateTime

  • Holds both Date and Time
  • Default format - yyyy-MM-dd-HH-mm-ss.zzz (2020-02-20T12:06:03.015)
  • LocalDateTime timestamp = LocalDateTime.now(); // gives timestamp now
  • //(year, month, date, hours, min, sec)
  • LocalDateTime dt1 = LocalDateTime.of(2011, 12, 30, 18, 20, 30);

Define Nashorn in Java 8

Nashorn is a JavaScript processing engine that is bundled with Java 8. It provides better compliance with ECMA (European Computer Manufacturers Association) normalized JavaScript specifications and better performance at run-time than older versions.

What is the use of JJS in Java 8?

As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript code in the console. Below is the example of CLI commands:

JAVA>jjs
jjs> print("Hello, Java 8 - I am the new JJS!")
Hello, Java 8 - I am the new JJS!
jjs> quit()
>>

 

Friday, December 27, 2019

Advanced Spring Boot Interview Questions


How Spring boot application handle the runtime exception internally and what are the annotation to use to declare the user define exception? Any real time scenario where spring boot fit to handle the exception.

Spring boot checks if any class is annotated as @ControllerAdvice and @ExceptionHandler and called from rest end point layer, when any exception occurs than spring boot calls the corresponding annotated class to handle the error message.
  • Spring boot provides the below annotation to create the custom handler which eventually catch the exception from rest endpoint.
  • Spring boot provides the cross-cutting concern to handle the exception being generated by rest layer.
  • Leverage to use the error message code comprehensively. 
  • @ControllerAdvice is an annotation, to handle the exceptions globally.
  • @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client.
The real-time scenario is like, let’s say that most of the exception message is system generated and has a straightforward information, which is sometimes difficult to interpret by the user interface and understand by layman user, to solve this issue spring boot handle the error message and convert into the meaningful and comprehensive message which easy to understand and interpret. 

What are the important annotations use to create the interceptor and what all their annotation does?

Interceptor is one of the prominent features of spring boot and must use the @Component annotated class that supports it and it should implement the HandlerInterceptor interface.
There are three methods which are used to implement the interceptor.
  • preHandle() method − This method is predominantly used  to perform the operation by intercepting the call and getting the information present in the request.
  • postHandle() method − This method is used  to perform the operation by intercepting  the call information present in the response.
  • afterCompletion() method − This is used to perform operations when the request and response get completed.

Spring boot example to develop the Exception handler?

Below code structure represent the ControllerAdvice  class developed using spring boot framework to handle the  exception.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
            // Need to mention the RestController so that it will behave as a controller class
@ControllerAdvice
public class ProductExceptionController {
// Below method use to handle the exception, which is being generated by the rent //endpoint method. This method also act as a User define exception.
  @ExceptionHandler(value = ProductNotfoundException.class)
  public ResponseEntity exception(ProductNotfoundException exception) {
     return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
  }
}
  1. Rest controller class which generate the exception
import java.util.HashMap;
import java.util.Map;
// Below series of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.demo.model.Product;
// This class represents how to call the exception handler class which is mention above.
@RestController
public class ProductServiceController {
  private static Map productRepo = new HashMap<>();
  static {
     Product honey = new Product();
     honey.setId("1");
     honey.setName("Honey");
     productRepo.put(honey.getId(), honey);
     Product almond = new Product();
     almond.setId("2");
     almond.setName("Almond");
     productRepo.put(almond.getId(), almond);
  }
  // Below rest end points method throwing the exception if id is not found in databases,   //so rather than call the runtime exception its calling the handler class, to catch the //exception and generate the appropriate message
  @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
  public ResponseEntity updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
     if(!productRepo.containsKey(id))
throw new ProductNotfoundException();
     productRepo.remove(id);
     product.setId(id);
     productRepo.put(id, product);
     return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
  }
}

 

What are Spring Profiles? How do you implement it using Spring Boot?
A profile is a feature of Spring framework that allows us to map the beans and components to certain profiles. A profile can be assumed to be a group or an environment like dev, test, prod, etc.; that needs a certain kind of behavior and/or requires to maintain distinct functionalities across the profiles. So, when the application is running with ‘dev’ (Development) profile only certain beans can be loaded and when in ‘prod’ (Production) certain other beans can be loaded.
In Spring Boot we use @Profile annotation to map bean to a particular profile by taking the names of one (or multiple) profiles.
Let’s say we have a Component class that is used to record and mock the REST requests and responses. However, we want to activate this component only in dev profile and disable in all other profiles. We annotate the bean with “dev” profile so that it will only be present in the container during development.
@Component
@Profile("dev")
public class DevMockUtility
Profiles are activated using application.yml in the Spring project:
spring.profiles.active=dev
To set profiles programmatically, we can also use the SpringApplication class:
SpringApplication.setAdditionalProfiles("dev");

 

What Is the Difference Between Hibernate and Spring Data JPA?
Hibernate is a JPA (Java Persistence API) implementation providing ORM (Object-relational mapping) for mapping, storing, updating and retrieving application data from relational databases to Java objects and vice versa. Hibernate maps Java classes to database tables and from Java data types to SQL data types, hence programmer is relieved from writing traditional data persistence programs like SQL.
Whereas Spring Data JPA is a JPA Data Access Abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. With Spring Data, we still need to use Hibernate, Eclipse Link, or any other JPA provider. One of the key benefits is that we can control transaction boundaries with the use of @Transactional annotation.

 

How to implement Caching in Spring Boot?

 

Caching is a mechanism that helps in reducing roundtrip calls to Database, REST service, files, etc. Performance under heavy load is a key feature expected from any modern web and mobile application, hence caching is really vital to enhance the speed of fetching data.
Spring Boot provides a starter project for caching “spring-boot-starter-cache”, adding this to an application brings in all the dependencies to enable JSR-107 (JCACHE - Java Temporary Caching API) and Spring caching annotations.
In order to enable caching in a Spring Boot application, we need to add @EnableCaching to the required configuration class. This will automatically configure a suitable CacheManager to serve as a provider for the cache.
Example:
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("addresses");
}
}
Now to enable caching, we need to add a @Cacheable annotation to the methods where we want to cache the data.
@Cacheable("addresses")
public String getAddress(Customer customer) {...}

 

What is HATEOS in RESTful applications?

 

HATEOAS (Hypermedia as the Engine of Application State) is a principle for REST APIs, according to which the API should guide the client through the application by returning relevant information about potential subsequent steps, along with the response.
This information is in the form of hypermedia links included with responses, which helps the client to navigate the site's REST interfaces. It essentially tells the clients what they can do next, and what is the URI of the resource. If a service consumer can use the links from the response to perform transactions, then it would not need to hardcode all links.
According to the Richardson Maturity Model, HATEOAS is considered the final level of REST.
To support HATEOAS, each resource in the application should contain a "links" property which defines hyperlinks to related resources. 
Each link object typically includes the following properties:
"rel”: Relation with the target resource.
"href”: URI for resource
For example:
{
 "contractId": 10067,
 "description": "Contract details for the requested orderId",
 "status": "created",
 "links": [
 {
"rel": "self",
    "href": "http://demoApplication.com/contracts/10067"}]
 }

 

Explain the difference between @Controller and @RestController annotation?

 

Traditional Spring controllers are created by adding a class with @Controller annotation. It is actually a specialization of the @Component annotation that allows the implementation classes to be autodetected by Spring context through the classpath scanning.
Generally, @Controller annotation is used in combination with @RequestMapping and @ResponseBody added to the request handling methods to define the REST APIs.
@RestController is a convenient annotation that combines both the features of @Controller and @ResponseBody annotations.
The key difference between typical Spring @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller returns the object and the object data is written directly to the HTTP response as JSON.

 

What is @Autowired annotation? How is @Qualifier used with it?

 

@Autowired annotation is used to autowire i.e. inject dependent bean on the constructor, setter method or a field/property. When @Autowired is used on dependency, the application context searches for a matching dependency and provides as required. This helps us to avoid writing explicit injection logic.
However, by default, all dependencies that are Autowired are required. So, in scenarios where a required dependency is not available or if there is conflict; it results in an exception like NoUniqueBeanDefinitionException.
There are a few options available to turn off the default behavior:
  1. By using (required=false) option with @Autowired to make it non-mandatory for a specific bean property.
@Autowired (required=false)
private Contract contractBean;
  1. By using @Qualifier, we can further qualify autowiring; in scenarios when two beans are created with the same name.
@Qualifier ("design")
private Contract contractBean

 

What is Microservices? How it is different from monolithic applications?

 

Microservices (MS) is an architecture pattern that prescribes to divide an application based on business functionality instead of technical boundaries.  These set of smaller interconnected services constitute the complete application. As opposed to monolithic architecture, it recommends breaking the application into smaller atomic units, each performing a single function.
Typically, an application provides a set of distinct features or functionality, such as order management, billing, customer service, etc. Each microservice works as a mini-application that has its own hexagonal architecture. It is often compared to Honeycombs (nests) that are a combination of multiple hexagonal structures.
Below are some of the key features of Microservices that distinguish from monolithic:
  1. Tight Cohesion: Single responsibility per service i.e. code perform a single and well-defined task only.
  2. Loose Coupling: Microservices are the autonomous i.e. effect of changes are isolated to that particular MS only.
  3. Interoperability: One of the key foci of microservices is on communication between systems using diverse technologies.
  4. Stateless: An ideal microservice does not have a state i.e. it does not store any information between requests. All the information needed to create a response is present in the request.
  5. Devops: It is highly recommended to implement an automated build and release process using suitable CI-CD infrastructure.
  6. Developing Products instead of Projects.

 

What is Hystrix and how it can be implemented in the Spring Boot application?

 

Netflix’s Hystrix is a library that provides an implementation of the Circuit Breaker pattern for Microservices based applications. A circuit breaker is a pattern that monitors for failures and once the failures reach a certain threshold, the circuit breaker trips, and all further calls will return with an error, without the external call being made at all.
On applying Hystrix circuit breaker to a method, it watches for failing calls to that method, and if failures build up to a threshold; Hystrix opens the circuit so that subsequent calls automatically fail.
While the circuit is open, Hystrix redirects call to a specified method called a fallback method. This creates a time buffer for the related service to recover from its failing state.
Below are the annotations used to enable Hystrix in a Spring Boot application:
@EnableCircuitBreaker: It is added to the main Application class for enabling Hystrix as a circuit breaker and to enable hystrix-javanica; which is a wrapper around native Hystrix required for using the annotations.
@HystrixCommand: This is method annotation that notifies Spring to wrap a particular method in a proxy connected to a circuit breaker so that Hystrix can monitor it. We also need to define a fallback method having the backup logic that needs to be executed in the failure scenario. Hystrix passes the control to this fallback method when the circuit is broken.
This annotation can also be used for asynchronous requests. Currently, it works only with classes marked with @Component or @Service.

 

What is Service Discovery and how it can be enabled in Spring Boot?

 

In a typical Microservice architecture multiple services collaborate to provide an overall functionality. These set of service instances may have dynamically assigned network locations. Also, the services scale up and down as per the load. It could get tricky in a cloud environment resolving the services that are required for operation for common functionality.
Consequently, in order for a client to make a request to a service, it must use a service-discovery mechanism. It is the process where services register with a central registry and other services query this registry for resolving dependencies.
A service registry is a highly available and up to date database containing the network locations of service instances. The two main service-discovery components are client-side discovery and service-side discovery.
Netflix Eureka is one of the popular Service Discovery Server and Client tools. Spring Cloud supports several annotations for enabling service discovery.  @EnableDiscoveryClient annotation allows the applications to query Discovery server to find required services.
In Kubernetes environments, service discovery is built-in, and it performs service instance registration and deregistration

 

What is Cloud Foundry?

 

Cloud Foundry is an open source cloud PaaS (platform as a service) where developers and organizations can build, deploy, run and scale their applications. It is the same company that manages Spring, hence has great support for running Spring based cloud applications.
For deploying an application in Cloud Foundry, we need to configure the application with a target and a space to deploy the application to.
It is increasingly gaining popularity as an open source and lets us use our own tools and code. Organizations can deploy Cloud Foundry PaaS on their own internal infrastructure; on cloud providers' infrastructure, such as Amazon Web Services (AWS) or Microsoft Azure.
It also provides a few out of the box components:
  1. Authentication: Contains an OAuth2 server and login server for user identity management.
  2. Application Lifecycle: Provides application deployment and management services.
  3. Application Storage and Execution: It can control when an application starts and stops, as well as the VM's containers.
  4. Service Brokers: Helps connecting applications to services like databases.
  5. Messaging: Enables VMs to communicate via HTTP or HTTPS protocols, can also store data like application status.
  6. Metrics and Logging. It provides Loggregator tool, which helps organizations monitor their Cloud Foundry environment.
It is very easy to set up and application on Cloud Foundry:
  1. Create a pivotal Cloud Foundry account.
  2. Create an organization and space to deploy the application.
  3. Add the plugin with the configuration of Cloud Foundry org and space in application pom.xml/build.gradle.

 

What is ELK stack?

 

Popular logging frameworks such as Log4j, Logback, and SLF4J, etc. provide logging functionality for the individual microservice application. However, when a group of run together to provide complete business functionality, it becomes really challenging to trace a request across all the services, especially in case of failures.
Hence it is highly recommended to have a centralized logging solution in place, to have all the log messages stored in a central location rather than on local machine/container of each microservice. This eliminates dependency on the local disk space (volumes) and can help retain the logs for a long time for analysis in the future.
The Elasticsearch, Logstash, and Kibana tools, collectively known as the ELK stack, provide an end-to-end logging solution in the distributed application; providing a centralized logging solution. ELK stack is one of the most commonly used architectures for custom logging management in cloud-based Microservices applications.
Elasticsearch is a NoSQL database used to store the logs as documents. Logstash is a log pipeline tool that accepts logs as input from various micro service applications, executes transformations if required and stores data into the target (Elasticsearch database).
Kibana is a UI that works on top of Elasticsearch, providing a visual representation of the logs and ability to search them as required.  All three tools are typically installed on a single server, known as the ELK server.
In a centralized logging approach, applications should follow a standard for log messages. Each log message having a context, message, and correlation ID. The context information is ideally can be the IP address, user information, process details, timestamp, etc. The message is a simple text description of the scenario. The correlation ID is dynamically generated and is common across all that used for end-to-end tracking of a request/task.