Showing posts with label Java Interview Question. Show all posts
Showing posts with label Java Interview Question. Show all posts

Sunday, September 4, 2016

Java Multi-threading Interview Questions and Answers - Series I

Java Multi-threading is quite tricky to understand. But if you understand its basics clearly, all other aspects to understand become so easy. Here are the first series of Java Multi-threading Interview Questions and Answers.

What are the different ways to create Threads in Java?

There are three ways to create threads in Java:
(a) By implementing runnable interface
(b) By extending Thread Class
(c) Using ThreadPoolExecutor to create one or more threads

Why the wait and notify methods are part of Object class and not Thread class?

For thread to go on wait state, its requires that it should wait on a particular Java Object so that the same object can be notified to make the thread back to runnable state. 

What is difference between wait and notify

wait method of Object class put the calling thread into wait state from running state whereas notify method put the waiting thread back to runnable state.

Tell me the difference between notify and notifyAll method

Suppose there are more than one threads waiting on an object, if we call notify method, only one thread will be back to runnable state out of n waiting threads. So the number of waiting threads will be  n - 1
notifyAll method will wake up all the threads waiting on an Object to the runnable state.

What is the benefit of concurrent classes

Java 5 provides a series of concurrent classes like ConcurrentHashMap and others, the benefit of which is that we can access those data-strucure classes simultaneously by multiple threads parallely without worrying about thread synchronization and we don't have to wait for one task to complete to start another.

How is HashMap different from ConcurrentHashMap

HashMap is not threadsafe i.e. the developer needs to take care of synchronization if multiple threads are accessing the HashMap whereas in Concurrent HashMap we dont have to worry about synchronization if multiple threads are accessing it.
Moreover, with no sychrnoziation overhead to be created by developer, ConcurrentHashMap is much faster than HashMap (considering we need to implement synchornization mechanism to work with HashMap)

Hashtable and ConcurrentHashMap both are threadsafe, which one  you will prefer

I will prefer ConcurrentHashMap because its performance is much faster as compared to Hashtable as all the methods of Hashtable are synchronized, there is overhead for acquiring and releasing object locks in Hashtable.
With multiple processor in place, apart from synchronization overhead, if multiple threads are calling the same method (for eg. put method), ConcurrentHashMap calls can go parallely and Hashtable calls needs to be executed synchronously.

How does String class is threadsafe if its internal implementation is not synchronized

String is a immutable class, so its value once set via constructor, it will not change and so all threads will see the same value and can be used across threads. This is true for every immutable class and we dont require synchronization to make it threadsafe. In other words, immutable class like String is a constant, so it can be safely used by multiple threads without fearing the change of value by one and dirty read by another (which is not possible here).

Do you need to hold lock of the object before you call Object.wait() or Object.notify()

Yes, for any call to wait and notify method, the calling thread must have the monitor lock with it. If we call it without having the monitor lock, it will throw exception.

If yes, then will Object.wait() will keep the lock forever

No, calling to Object.wait() will put the current thread in wait state waiting for notify on that object and release the lock by current thread immediately.

What is Deadlock

Deadlock is the situation where one thread is holding a resource and waiting for another resource and the other thread is holding that another resource and waiting for a resource. This situation is called deadlock.

What is Atomic in java

Java 5 introduce Atomic Variable such as AtomicInteger, AtomicLong and others. The benefit of using Atomic classes is that its operation cannot be interrupted in between. For example, i++ is a three step operation, fetching value of i from memory, increasing its value and putting back new value of i in memory. Any other thread can interrupt in between three calls whereas with Atomic classes it is just a one cpu call (all three combined), so a similar operation like i++ in AtomicInteger cannot be interrupted.

Will declaring a variable as volatile makes it a threadsafe

No, declaring a variable as volatile will only make sure that the it will always reads the memory value of variable and not the local thread cache. This means that if some other thread has updated the value, the current thread will only read the updated one (local cache copy may be dirty in this case). This in no case will make it threadsafe because changes by two threads can be overwritten by each other even though both threads are reading the in-memory data.
The benefit of using volatile in multi-threaded environment is that if one thread is making changes to a variable and other threads are only reading it, the changes made by that thread will be immediately visible to other threads.

That's all for Series -I of Core Java Multi-threading Interview Questions with Answers. If you are looking for all Java Interview questions, here is the link.

Sunday, July 3, 2016

JBOSS Interview Questions and Answers

JBOSS Application server has a new name WildFly and it implements JAVAEE specification. For interview purpose, here are some questions along with its answers.

What is JBOSS? 

JBoss is an open source application server based on JaVA EE technology. Being JAVAEE based, it can run on cross-platform. It was embedded with Apache Tomcat web server. It runs under any JRE version of 1.3 or later . JBoss supports JNDI, Servlet/JSP (Tomcat or Jetty), EJB, JTS/JTA, JCA, JMS, Clustering (JavaGroups), Web Services (Axis), and IIOP integration (JacORB).

Define JBoss cache? 

Caching usuall comes into picture when there are frequent access to some objects. Likewise, multiple and frequently accessed Java objects are cached by using JBoss cache to improve the performance of e-business applications. 

What is JBoss JBPM? 

JBoss JBPM is a workflow and Business Process Manager engine. As a BPM engine, it enables the creation of business processes that coordinates between people, applications and services. The combination of workflow applications development with process design is a feature of JBoss jBPM. The business process has GUI (Graphical User Interface) to facilitate a strong link between the business analyst and technical developer. This feature is provided by the JBoss jBPM process designer.


At first, you need to measure different components of the application and then observe where the degradation is, and whether it is internal or external and which component is consuming maximum cpu. Using Joss JMX agents and monitoring the deployed components to the application server involves in the first step.

After observing which specific components or libraries spent most of time, one can then use Jprobe to examine that single object or the objects loaded in the memory.

What is JTA? 

Java Transaction API (JTA) specifies standard Java interfaces between a transaction manager and the parties involved in a distributed transaction system: the resource manager, the application server, and the transactional applications. It allows applications to perform distributed transactions, that is, transactions that access and update data on two or more resources.It consists of three elements: a high-level application transaction demarcation interface, a high-level transaction manager interface intended for an application server, and a standard Java mapping of the X/Open XA protocol intended for a transactional resource manager.

Which Hibernate object wraps the JDBC Connection? 

The Session interface wraps a JDBC Connection which is a single threaded object representing a single unit for application and persistent database. You can get the Session object from SessionFactory's openSession() method

Is the Session Factory Thread safe? 

Yes because many threads can simultaneously access it and request for sessions. It holds cached data that has been read in one unit of work and is likely to be reused in future unit of work. The best practice to create Session Factory object is when the application is initialized.

How can you start a JTA transaction from a Servlet deployed on JBoss? 


What if you need to span your transaction across multiple Servlet invocations?


What are the differences between EJB 3.0 and EJB 2.0? 

EJBs are now plain old Java objects (POJO) that expose regular business interfaces (POJO), and there is no requirement for home interfaces.
  • Reduction in the requirements for usage of checked exception.

What is the difference between a local-tx-datasource and a xa-datasource? can you use transactions in both? 

A local-tx-datasource identifies a data source that uses transactions, even distributed trans actions within the local application server, but doesn’t use distributed transactions among multiple application servers. An xa-datasource on the other hand identifies a data source that uses distributed transaction among multiple application servers.

What do you need to set-up a cluster with JBoss? 

Basically starting JBoss with the “all” configuration contains everything needed for clustering:
It has all the libraries for clustering:
  • JGroups.jar, jboss-cache.jar
  • Clustered beans (cluster-service.xml)
  • HTTP session replications (tc5-cluster-service.xml)
  • Farming
  • HA-JMS


You could activate the "Commit Option A" that is the container caches entity bean state between transactions. This option assumesthat the container has exclusive access to the persistentstore and therefore it doesn’t need to synchronizethe in-memory bean state from the persistent store at the beginning of each transaction.

Which component handles cluster communication in JBoss?


Is it possible to put a JBOSS server instance into multiple cluster at the same time? 

It is technically possible to put a JBOSS server instance into multiple clusters at the same time, this practice is generally not recommended, as it increases the management complexity.

What do you know about Seam? 

Built on the standards JavaServer Faces and EJB 3.0, JBoss Seam unifies component and programming models and delivers a consistent and powerful framework for rapid creation of web applications with Java EE 5.0. Seam simplifies web application development and enables new functionality that was difficult to implement by hand before, such as stateful conversations, multi-window operation, and handling concurrent fine-grained AJAX requests. Seam also unifies and integrates popular open source technologies like Facelets, Hibernate, iText, and Lucene.

Does Seam run on other application servers besides JBOSS?

Seam runs beautifully on other application servers - just like everything else the Hibernate team does, this is not a JBoss-only thing.

Which JDK is needed to run Seam? 

Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0 features.

How would you convince my IT department to adopt SOA? 



What do you think about BPEL and BPM ? How do they compare? 

In my opinion BPEL and BPM are quite different things so they cannot even be compared. The problems boils down to the fact that these years maybe BPEL has been marketed for something which isn't: that is a Business Process Management framework.
BPEL is made up for service orchestration, that is publishing new services as a function of other services.
while BPM si needed for handling human task management functionalities and subprocess management.

What is the difference between JAX--WS and JAX-RPC? 



Do you know how you could add support for Web Service transactions? 


What version of JBoss AS do I need to run Seam? 


For Seam 1.2: Since Seam requires the latest edition of EJB3, you need to install JBoss AS from the latest JEMS installer. Make sure that you select the "ejb3" or "ejb3+clustering" profile to include EJB3 support. Also, the jboss-seam.jar library file from the Seam distribution must be included in each Seam application you deploy. Refer to examples in Seam distribution (inside the examples directory) to see how to build and package Seam applications.

Can I run Seam outside of JBoss AS? 

Yes, you can run Seam applications in plain Tomcat 5.5+ or in the Sun GlassFish application server. To run Seam application in Tomcat, you need a number of additional library files and a few configuration files to bootstrap the JBoss EJB3 inside Tomcat. Please refer to the deploy.tomcat ANT build target for the Seam booking example (in the examples/booking directory of the Seam distribution) for more on how to build a Tomcat WAR for Seam applications. Refer to this blog post on how to run Seam in Sun's Glassfish application server.

Can I run Seam in a JAVAEE environment? 

Yes, as of Seam 1.1, you can use Seam in any JAVAEE application server, with one caveat: you will not be able to use EJB 3.0 session beans. However, you can use either Hibernate or JPA for persistence, and you can use Seam JavaBean components instead of session beans.

Can I run Seam with JDK 1.4 and earlier? 

No, Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0 features.

Where can I find Seam examples and documentation? 

The source code and build script of all Seam example applications are included in the examples directory of the Seam distribution.

Is it true that Seam only works with JSF? 

Seam only supports JSF as a view framework at this time. We plan to support other web frameworks in the future. We like JSF because it is a component-based UI framework, which fits really well with Seam's component-based approach to business objects and persistence objects. Seam made a major improvement to JSF by eliminating almost all XML configuration for backing beans i.e. you can now define back beans from POJOs or EJB3 components using simple annotations. We recommend you use Facelets, instead of JSP, with JSF. Facelets provide a powerful templating framework, better appplication performance, and allows us to write much simpler JSF pages. 

Can I use AJAX with Seam? 

A: Yes, Seam provides excellent support for AJAX. First, Seam supports the ICEfaces and Ajax4JSF Ajax component libraries for JSF. If you prefer a more "old fashioned" approach, Seam provides a complete JavaScript remoting framework which lets you call Seam components and subscribe to JMS topics directly from the client. 

Can I unit test Seam applications without starting the Application Server?

Yes, Seam provides its own integration test framework based on TestNG. You can easily mock all Seam services using those facilities without ever loading an application server or a database.

Thursday, March 24, 2016

JSF Interview Questions And Answers

What is JSF?

JavaServer Faces is a specification for building web based UI (User Interface) for Java Web Applications. It has been made as a standard for Java Community Process. JSF provides widgets like buttons, hyperlinks, checkboxes, etc. in different ways. It has extensible facilities for validating inputs and converting objects to and from strings for display.

What is JavaServer Faces event and listener model?

It provides way to determine the way events emitted by JavaServer Faces UI components are handled.

What is JavaServer Faces conversion model?

JSF conversion model provides way to convert string-based markup generated by JavaServer Faces UI components and server-side Java components (objects) and vice-versa.

What is JavaServer Faces UI class?

JavaServer Faces UI component class defines the properties and behaviour of a JavaServer Faces UI component.

Define JavaServer Faces expression language?

To bind the associated component to a bean property or to bind the associated component's value to a method or an external data source, such as a bean property, simple expression language is being used by a JavaServer Faces UI component tag attributes.

What is JSF life cycle and its phases?

(i) Restore view phase
(ii) Apply request values phase
(iii) Process validations phase
(iv) Update model values phase
(v) Invoke application phase
(vi) Render response phase.

What are tags in JSF?

To enhance the view of the JSP Pages, JSF tags are generally used. Remember JSP pages represent views. Each tag gives rise to an associated component. JSF provides 43 tags in two standard JSF tag libraries: 1. JSF Core Tags Library 2. JSF Html Tags Library.

Thursday, February 18, 2016

Java Interview Questions on Atomic variables

Here are the list of 5 good questions on Volatile and Synchronized keywords in Java:

1. What is Atomic variables and its significance:

Atomic variables performs atomic operation on its object. In other words, it operation will happen completely or will not happen at all, and no one can interrupt its operation in between. With its introduction in Java 1.5, it is being widely used in multi-thread environment without any synchronization.

2. Is Atomic variable more faster or variable through synchronized code?

For read access, it does not matter whether it is atomic or non-atomic, synchronized or non-synchronized. For write access, atomic variable does not require lock to write because all update to variable happens atomic (either happened or not happened completely) For eg: suppose you want to do i++ in a multi-threaded application and multiple threads can call this, you need to synchronized i++ call (as it is set to 3 registry levels call and you know it can be context switch at any point of registry level calls even in between) to avoid dirty reads and inconsistent write. Atomic variable has just 1 registry level calls.

3. What is the disadvantage of Atomic variables as compared to its primitive type?

All Objects in java requires more care by the programmer to avoid memory consistency errors, doesnt matter whether it is Atomic or not. While the siblings of Atomic variable can be primitive and not object, it doesn't falls into object category and hence not required to take care of memory consistency error The reason why every object requires to avoid memory consistency errors in multi-threaded application is because each thread stack caches the copy of object locally on thread stack (Runtime optimization) might result into not in sync with actual copy of heap if it gets modified by another thread (even in the same code but different thread stack). One solution to avoid is to use volatile for that object which can be changed by another thread frequently. Also the local copy tries to in sync with heap copy very fast but problem occurs if your thread access it more faster than sync happens.

4. How Atomic variables are implemented internally or how atomic variables achieves atomicity?

With the introduction of additional register being added to cpu, atomic variables harness it to achieve atomicity. Since its just 1 cpu register call, it cannot be interrupted in between.

5. What are the atomic variable classes in java?

There are only two classes: AtomicInteger and AtomicLong. There is no atomic level classes for other primitives like double, float etc.

Spring boot Interview Questions and Answers

What is Spring Boot?

Spring boot is the solution for creating standalone and production grade Spring application with very little Spring configuration.

Explain some features of Spring Boot?

Here are some features of Spring Boot:
  • It embeds web-application like Tomcat or Jetty directly
  • Comes with various already available maven's POM file to do minimal build creation code.
  • Automatically configure Spring
  • Provides inbuilt health-check feature
  • Provides inbuilt 'metrics' feature

What is the advantage of Spring Boot?

Following are the advantages of using Spring Boot:
  • Reduces lots of development time by providing boilerplate Java code and configuration
  • Easy to integrate with Spring ORM, Spring Security, Spring JDBC etc
  • Provides various plugins to develop, build and unit test Spring Boot applications with minimum effort.

Explain the purpose of spring-boot-starter-batch?

The purpose of spring-boot-starter-batch is to import all the dependency for the spring batch application. The advantage of it is that searching and configuring all the dependencies has become easier.

What are the template engines that Spring boot supports?

Spring boot supports the following template engines:
  • Groovy
  • FreeMarker
  • Mustache

What is the main disadvantage of Spring Boot?

Converting legacy Spring Framework application into Spring Boot application is not straight forward and is bit time consuming, which makes it difficult to port legacy Spring projects to Spring Boot application.

That's all for interview questions and answers on Spring Boot. Please provide your feedback in comment section.

Wednesday, February 10, 2016

Daemon Thread in java



How to create a Daemon Thread in Java:


Code Example:

public class DaemonThread {

public static void main(String[] args) {
System.out.println("Entering Main Thread");
Thread t = new Thread(new Runnable(){
public void run() {
System.out.println("Executing Daemon Thread");
try {
} catch (InterruptedException e) {
t.setDaemon(true); // Thread becomes daemon thread here
System.out.println("Exiting Main Thread");

Here is the sample output:

Entering Main Thread
Exiting Main Thread

Entering Main Thread
Exiting Main Thread
Executing Daemon Thread
Executing Daemon Thread



The above code example and output illustrates the following:
  • JVM doesn't wait for the daemon thread to complete its task
  • Daemon thread dies as soon as JVM exits

Finding if the thread is daemon or not:
