Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Wednesday, August 5, 2020

Java Technical interview @ Candela Labs - Round 2

Hi friends,

In this post , I am sharing interview questions answers asked in Candela Labs in round - 2.



Question 1:

Is the DispatcherServlet instantiated via Application context?

Answer:

No,the DispatcherServlet is instantiated by Servlet containers like tomcat or jetty. We must define the Dispatcher Servlet into the web.xml file.

We also include load-on-startup tag = 1, which means DispatcherServlet  is instantiated when you deploy the spring MVC application to Tomcat or any other servlet container.
During instantiation, it looks for a file servlet-name-context.xml and then initializes beans defined in this file. 



Question 2:

Do we need spring-mvc.jar in our classpath or is it part of spring-core?

Answer: 

The spring-mvc.jar is not part of spring-core, which means that if we want to use spring MVC framework in the java project, we must include spring-mvc.jar in the application's classpath.
In a java web application, spring-mvc.jar is usually placed inside the /WEB-INF/lib folder.



Question 3:

How Spring MVC framework works? How HTTP request is processed?

Answer:

  • Client sends a request to a URL.
  • That request hit the web container e.g. Tomcat or Jetty. Then it looks into web.xml and find the servlet or filter which is mapped to that URL.
  • It then delegates the control to servlet or filter to process the request. Web container(Tomcat) is responsible for creating servlet and filter instances and invoking their various lifecycle methods e.g. init(), service() and destroy().  In the case of HTTP request, HTTPServlet handles that and depending upon the HTTP request method, various do...() methods are invoked by container e.g. doGet(), doPost() to process GET request and POST request.
  • To enable spring MVC, we need to declare the DispatcherServlet from spring MVC jar into web.xml. This servlet listens for a URL pattern * as shown below in web.xml, which means all requests are mapped to DispatcherServlet.
  •     Then DispatcherServlet then passes the request to a specific controller depending on the URL requested. It uses handler mapping [@RequestMapping annotation] or spring mvc configuration file to find out the mapping of request URL to difference controllers. Controller classes are also identified using @Controller and @RestController annotations.
  • After processing the request , controller returns a logical view name and model to DispatcherServlet and it consults view resolvers until an actual view is determined to render the output.
  • DispatcherServlet then contacts the chosen view e.g. Freemarker  or JSP with model data and it renders the output.
  • This rendered output is returned to the client as HTTP response. On it's way back, it can pass to any configured filgter as well e.g. Spring security filter chain or filters configured to convert the response to JSON or XML.



Question 4:

Which cache you have used and explain the steps to use that cache?

Answer:

There are multiple types of caches:

  • Caffeine
  • HazelCast
  • Redis
  • EHCache
  • CouchBase
I have used Redis cache.

Redis is an open source in-memory data structure store used as a database, cache and message broker.

It supports data structures such as strings, hashes, lists, set, sorted set and streams.
Redis has built-in replication.

Redis cache limits:

On 32-bit machine,it can store upto 3 GB of data. When cache size reaches the memory limit, old data is removed to make place for new one.

Annotations used:

  • @Cacheable : To cache some values
  • @Cacheput : To update the cache
  • @CacheEvict : To empty the cache

Maven Dependency:

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


application properties:

#Redis config:
spring.cache.type=redis
spring.redis.host-localhost
sprint.redis.port=6379


@EnableCaching annotation on SpringBootApplication main class.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository{

}

@RestController
public class UserController{

    private final Logger log = LoggerFactory.getLogger(getClass());

    private final UserRepository userRepository;

    @Autowired
    public UserController(userRepository userRepository){
    
        this.userRepository = userRepository;
    }

    @Cacheable(value="users", key="#userId", unless="#result.followers<12000")
    @RequestMapping(value"/{userId}", method=RequestMethod.GET)
    public user getUser(@PathVariable String userId){

        log.info("Getting user with ID {}", userId);
        return userRepository.findOne(Long.valueOf(userId));
    }
}



Question 5:

What will be the output of below code?

public class StringClass{

    public static void main(int[] args){

        final String str = "First String is computer";
        String str1 = str.replaceAll("First", "Last");

        System.out.println(str);
    }

}

Answer:

It says, main type is not found. Because JVM requires a main method with String[] as arguments.
In the same code, if we try replacing str1 with str, then compiler shows exception that str is declared as final and cannot be changed.



Question 6:

What happens internally when we invoke main method?

Answer:

The purpose of main method in java is to be program execution start point.

When we run java.exe,it makes some JNI calls. These calls load the DLL that is really the JVM.

It will parse the command line arguments , creates a new string array in the JVM to hold these arguments , parses the class name that we specify as containing main() method, uses JNI calls to find the main() method, then invokes the main() method passing the parameters list.



Thanks for reading!!

Tuesday, August 4, 2020

Java Technical Interview @ CandelaLabs

Hi Friends,

In this post, I'm sharing interview questions answers asked in telephonic round of CandelaLabs.

You can also read my other interviews:



Question1: 

What is DispatcherServlet and why it is used for?

Answer:

The DispatcherServlet is the implementation of front controller design pattern that handles all incoming web requests to a spring MVC application.
A front controller pattern is a common pattern in web applications whose job is to receive all requests and route it to different components of application for actual processing.

In Spring MVC, the DispatcherServlet routes web requests to spring MVC controllers.

DispatcherServlet uses handler mapping like @RequestMapping annotation to find correct controller to process a request.

It s also responsible for delegating logical view name to ViewResolver and then sending the rendered response to the client.



Question 2:

What is the root application context in spring MVC? How is it loaded?

Answer:

In Spring MVC, the context loaded using ContextLoaderListener  is called the root application context which belongs to the whole application. While the one initialized using DispatcherServlet is actually specific to that servlet.

Technically, spring MVC allows multiple DispatcherServlet in a spring MVC web application and so are multiple contexts , each specific for the specific servlet. 



Question 3:

How many types of Dependency injection types are there in Spring?
 
Answer:

Spring documentation strictly defines only twp types of injection : constructor and setter injection.

However there are more ways to inject a dependency like a field injection , lookup method injection.

Constructor Injection: Enforcing immutability:

In this, a dependent class has a constructor , where all dependencies are set. These will be provided by spring container according to xml, java or annotation based configuration.

 e.g.:

class Service1{

}

class Service2{

}

class DependentService{
    private Service1 ser1;
    private Service2 ser2;

    public DependentService(Service ser1, Service2 ser2){
        this.ser1 = ser1;
        this.ser2 = ser2;
    }
}


public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathApplicationContext("spring.xml");

        (DependentService) container.getBean("dependentService");
    }
}


spring.xml is:

<?xml version = "1.0" encoding = "utf-8"?>
    // bean xmlns namespaces goes here.....

    <bean id = "service1" classs ="eample.service1"/>
    <bean id = "service2" class = "example.service2"/>

    <bean id="deoenddentService" class = "example.DepenentService">
        <constructor-arg type = "example.Service1" ref = "service1"/>
        <constructor-arg type = "example.Service2" ref = "service2"/>
    </bean>



Constructor injection using annotation:

@Service
class Service1{

}

@Service
class Service2{

}

@Service
class DependentService{

    private final Service1 ser1;
    private final Service2 ser2;

    @Autowired
    public DependentService(Service1 ser1, Service2 ser2){
        
        this.ser1 = ser1;
        this.ser2 = ser2;
    }

}

public class Main{

    public static void main(String[] args){

        ApplicationContext container = new ClassPathAppplicationContext("spring.xml");
        (DependentService) container.getBean("dependentService");
    
    }
}

Now in spring.xml file:

we do not need to add any <bean>.

Just add <context:component-scan base-package= "example"/>

Drawback of this approach: 

We need to use @Qualifier annotation to tell spring, which implementation of a specific interface to use , in case w e are using two implementations of an interface.

Higher chance to have circular dependencies.


Note: We can have many more constructors in or class, but only one of them should qualify for dependency injection.


Advantage of this approach: Can be combined with setter injection and field injection.


Setter injection:

With XML:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    public void setService1(Service1 ser1){

        this.ser1 = ser1;
    }

    public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}

XML is:

<bean id = "service1" class = "example.Service1"/>
<bean id= "service2" class = "example.Service2"/>

<bean id = "dependentService" class = "example.DependentService">
    <property name="service1" ref="service1"/>
    <property name="service2" ref="service2"/>
</bean>


Setter Injection with annotations:

class Service1{

}


class Service2{

}

class DependentService{

    private Service1 ser1;
    private Service2 ser2;

    public DependentService(){

        
    }

    @Autowired
    public void serService1(Service1 ser1){

        this.ser1 = ser1;
    }

     @Autowired
     public void setService2(Service2 ser2){
    
        this.ser2 = ser2;
    }

}


Note: We can combine setter injection and constructor injection.

  
Field Injection:

@Service
class DependentService{

    @Autowired
    private Service1 ser1;
    
    @Autowired
    private Service2 ser2;
}


Advantages:

  • Easy to use. No constructors or setters required.
  • Can be easily combined with the constructor and /or setter approach.

Disadvantages:

  • A number of dependencies can reach dozens until we notice that something went wrong in the design.



Question 4:

What are java Microservices frameworks?

Answer:

There are multiple java microservices frameworks:

  • Spring and Spring boot
  • DropWizard
  • Eclipse MicroProfile

Spring and Spring Boot:

    The framework propagates building the application into a jar and running it on the embedded Tomcat server , making it a perfect combination with Docker to manage a virtualized  deployment environment.

DropWizard:

Like Spring boot, DropWizard application is packages into jar file with the jetty server embedded.

DropWizard integrates the tried-and-tested java libraries into a fully functional platform: Jersey for REST, Jackson for JSON, Freemarker for template   and Mustache for java based UIs.

DropWizard ships with no built-in dependency injection solution, but integrations exist for Guice and Dagger.




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!!

Tuesday, January 21, 2020

Java Interview @ CapGemini

Hi Friends,

I hope you have read my previous posts on Java interviews:


In this post, I'm sharing java questions asked in Aricent @ experience of 11 years.




Question 1:

How to handle transaction in Spring?

Answer:

In Spring, there are two ways of managing transactions:


  • Programmatically manage by writing custom code
  • Using Spring to manage transaction
    • Programmatic Transaction management
    • Declarative Transaction management


Programmatically manage by writing custom code:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistance_unit_name");
EntityManager entityManager = factory.createEntityManager();
Transaction transaction = entityManager.getTransaction();

try{
    transaction.begin();
    //..........Business logic
    transaction.commit();
}
catch(Exception e){
    transaction.rollback();
    throw e;
}

Pros:

  • The scope of the transaction is very clear in the code
Cons:
  • It's repetitive and error prone
  • Any error can have a very high impact
  • A lot of boilerplate code needs to be written and if you want to call any another method from this method, then again you need to manage it in the code.


Using Spring to manage transaction:

1. Programmatic Transaction Management:
  • Using the transaction template
  • Using a PlatformTransactionManager implementation directly
2. Declarative Transaction




Question 2:

What is ORM and how to use it?

Answer:

ORM means Object Relational Mapping. It is a tool that helps in interacting with the database.

for example JPA is an ORM  which specifies some specifications which needs to be implemented.
In Spring, Hibernate is the implementation of JPA specifications.




So using ORM, Java object is mapped to relational table in database.




Question 3:

What is Heap dump?

Answer:

Heap Dump:  It is a snapshot of the memory of a java process.
This snapshot contains information about java objects and classes in the heap at the moment the snapshot is triggered.

Typically , a full GC is triggered before the heap dump is written, so the heap dump contains information about the remaining objects in the heap.

Typical information in a heap dump are:

  • All objects: Class, fields, primitive values and references
  • All Classes: Class Loader, name, super class and static fields
  • Garbage collection roots: It is an object that is accessible from outside the heap.




Question 4:

Memory management in Java 8?

Answer:





Perm Gen in java 7 and earlier version has a default maximum size of 64 MB for 32-bit machine and 84 MB for 64-bit machine.
While default maximum size for metaspace is unlimited.

In java 8 ,we can set the initial and maximum size of metaspace using:

-XX:MetaspaceSize = N : Sets the initial and minimum size of metaspace
-XX:MaxMetaspaceSize=N : Sets the maximum size of the metaspace



Question 5:

Difference between Serial and Parallel streams.


Answer:

Parallel streams divide the task into many and run them in different threads, using multiple cores of the computer. It uses main thread along with ForkJoinPool.commonPool worker threads.

Sequential stream uses a single core. So it uses only 1 thread that is main thread.






Question 6:

How to find OutOfMemoryError in production app? And how to avoid this error immediately for long time?


Answer:

If we face OutOfMemoryError in production and we cannot really reason about it from stacktraces or logs, we need to analyze what was in there.

Get the VM Heap dump on OOM:


  • -XX:+HeapDumpOnOutOfMemoryError
  • -XX:HeapDumpPath="/tmp"
And use that for analysis. We can use memory analyzer tool for this.

How to avoid this error immediately for long time?

We can increase Heap space using -XX argument  for a while and it will work fine.


Question 7:

What is internal structure of heap memory?


Answer:






Question 8:

How to configure GC in Java application?

Answer:

GC tuning is only required when we have not set memory size in the application and too many Timeout logs are printed.






Question 9:

What are Serial and Parallel GC's?


Answer:

Serial Collector:

  • Used for single threaded environments [32-bit Windows] and apps that use small heap
  • It stops all threads when it is running. Means it is not suitable for server environment.
  • We can use it by turning on the -XX:+UseSerialGC JVM argument.

Parallel Collector:
  • This is JVM's default garbage collector
  • It uses multiple threads to scan through and compact the heap and speeds up garbage collection.
  • The downside is that it will stop application threads when performing either a minor GC or full GC.
  • It is best suited for apps that can tolerate application pauses.
  • Although it is default collector, but it can be configured using -XX:UseParallelGC JVM argument



Question 10:


What is Java Memory model?


Answer:






That's all for this interview.

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...