Interface Java Interview Questions – Set 13

Which one would you prefer and why

The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice.

Also note how the threads are started in each of the different cases as shown inthe code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior.

By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.

What are the different types of IoC (dependency injection

There are three types of dependency injection:

  • Constructor Injection(e.g. Spring): Dependencies are provided as constructor parameters.
  • Setter Injection(e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection(e.g. Avalon): Injection is done through an interface.

Can you describe the architecture of a medium-to-large scale system that you actually designed or implemented? Can you white board the components of the system you recently worked on? How would you go about designing a JEE shopping cart application? Can you discuss some of the high level architectures you are experienced with

There are a number of high level conceptual architectures as discussed below. These individual architectures can be mixed and matched to produce hybrid architectures.

Model-View-Controller Architecture

Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC frameworks and Swing GUI.

  • The model represents the core business logic and state.
  • The view renders the content of the model state by adding display logic.
  • The controller translates the interaction with the view into action to be performed by the model.

The actions performed by a model include executing the business logic  and changing the state of the model.Based on the user interactions, the controller selects an appropriate view to render.The controller decouples the model from the view.

Service Oriented Architecture (SOA)

The business logic and application state are exposed as reusable services.

An Enterprise Service Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the services.

The above architecture has 5 tiers. The application tier could be using a typical MVC architecture.

  • The service orchestration tier could be using ESB products like OracleService Bus, TIBCO, etc and BPM products like Lombardi BPM, Pega BPM, etc.
  • In the abovediagram, the ESB integrates with the BPM via messaging queues.
  • The service tier consists of individual services that can be accessed through SOAP or RESTful web services.
  • The SOA implementation requires change agents to drive adoption of new approaches.
  • The BPM,application integration, and real-time information all contribute to dynamically changing how business users do their jobs.

So, it needs full support from the business, requiring  restructuring and also it can take some time to realize the benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments SOA as an architectural style. Cloud computing is expected to provide a computing capability that can scale up (to massive proportions) or scale down dynamically based on demand. This implies a very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e on the cloud).

User Interface (UI) Component Architecture

This architecture is driven by a user interface that is made up of a number of discrete components.Each component calls a service that encapsulates business logic and hides lower level details. Components can be combined to form new composite components allowing richer functionality. These components can also be shared across a number ofapplications.

For example, JavaScript widgets, Java Server Faces (JSF) components, etc.

RESTful data composition Architecture

The user interface can be built by calling a number of underlying services that are each responsible for building part of a page.

The user interface translates and combine the data in different formats like XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail messages and calendar applications), RSS (for generating RSS feeds), etc.

HTML composition Architecture

In this architecture, multiple applications output fragments of HTML that are combined to generate the final user interface.

For example, Java portlets used inside a portal application server to aggregate individual content..

Plug-in Architecture

In this architecture, a core application defines an interface, and the functionality will be implemented as a set of plug-ins that conform to that interface.

For example, the the Eclipse RCP framework, Maven build tool, etc use this architecture.

Event Driven Architecture (EDA)

The EDA pattern decouples the interactions between the event publishers and the event consumers. Many to many communications are achieved via a topic, where one specific event can be consumed by many subscribers. The EDA also supports asynchronous operations and acknowledgments through event messaging.

This architecture requires effective monitoring in place to track queue depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an event can be difficult in some cases. This architecture is useful in scenarios where the business process is inherently asynchronous, multiple consumers are interested in an event(e.g. order status has changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with the booking details and itinerary), and real-time request/response is not required (e.g. a long running report can be generated asynchronously and made available later via online or via email).

Most conceptual architectures use a hybrid approach using a combination of different architectures based on the benefits of each approach and its pertinence to your situation. Here is a sample hybrid approach depicting an online trading system.

FIX is a Financial Information eXchange protocol. You could also notice a number of synchronous calls using XML/HTTP or SOAP/HTTP and asynchronous calls using JMS. The above diagram also depicts that an enterprise architecture can be complex with a number of moving parts. So, it is imperative that all these moving parts are properly monitored and tested for any potential performance issues. Most of these services will be running as a cluster or a load balanced service with either active/active or active.passive configuration for high availability and scalability.

How to find a deadlock has occurred in Java? How to detect a Deadlock in Java

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.

  • findMonitorDeadlockedThreads() – This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
  • findDeadlockedThreads() – It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM

The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use.

Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language andplatform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.

Explain different way of using thread

A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.

What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container

Dependency Inversion Principle (DIP) is a design principle which is in some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesn’t say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind.

The Dependency Inversion Principle (DIP) states that High level modules should not depend upon low level modules. Both should depend upon abstractions.Abstractions should not depend upon details. Details should depend upon abstractions.When this principle is applied, the higher level classes will not be working directly with the lower level classes, but with anabstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP.

Firstly define the abstraction layer.

package principle_dip2;

public interface AnimalHandler {

public abstract void handle( );

}

package principle_dip2;

public interface AnimalHelper {

public abstract void help( );

}

Now the implementation that depends on the abstraction as opposed to the implementation.

package principle_dip2;

public class CircusService {

AnimalHandler handler;

public void setHandler(AnimalHandler handler) {

this.handler = handler;

}

public void showStarts( ) {

//code omitted for brevity

handler.handle( );

}

}

package principle_dip2;

public class TigerHandler implements AnimalHandler{

AnimalHelper helper;

public void setHelper(AnimalHelper helper) {

this.helper = helper;

}

public void handle( ){

//…

helper.help( );

//…

}

}

package principle_dip2;

public class TigerHelper implements AnimalHelper{

public void help( ){

//……

}

}

Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the  Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes).

The Inversion of Control Container (IoC) is a container that supports Dependency Injection. In this you use a central container  like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

The real power of DI and IoC is realized  in its ability to replace the compile time binding of the relationships between classes with  binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them.

Note: The CDI (Contexts and Dependency Injection)  is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI.

In your experience, why would you use Spring framework

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don’t need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

Spring framework’s core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building ‘mock’ objects implementing the interfaces expected by yourapplication logic. DI code is much easier to reuse as the ‘depended’ functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separatingapplication business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it’s simplicity. Simplicity means more readable and maintainable code.When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC webframework, and integration to other frameworks likeHibernate,iBatis,JasperReports,JSF,Struts,Tapestry,Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle’s Coherance.Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.

Explain different ways of creating a thread

Threads can be used by either:

  • Extending the Thread class.
  • Implementing the Runnable interface.

Using the Executor framework

(this creates a thread pool)

By extends:

class Counter extends Thread {

//method where the thread execution will start

public void run(){

//logic to execute in a thread

}

//let’s see how to start the threads

public static void main(String[] args){

Thread t1 = new Counter();

Thread t2 = new Counter();

t1.start();  //start the first thread. This calls the run() method.

t2.start(); //this starts the 2nd thread. This calls the run() method.

}

}

By implements:

class Counter extends Base implements Runnable{

//method where the thread execution will start

public void run(){

//logic to execute in a thread

}

//let us see how to start the threads

public static void main(String[] args){

Thread t1 = new Thread(new Counter());

Thread t2 = new Thread(new Counter());

t1.start();  //start the first thread. This calls the run() method.

t2.start();  //this starts the 2nd thread. This calls the run() method.

}

}

The thread pool is more efficient and  learn why and how to create pool of  threads using the executor framework

.

Why do we need run() & start() method both. Can we achieve it with only run method

We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.

What are the Core interfaces are of Hibernate framework

The core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  • Session interface
  • SessionFactory interface
  • Transaction interface
  • Query and Criteria interfaces