Sei sulla pagina 1di 60

Top 50 Java Thread Interview Questions

Answers for Experienced


Read more: http://javarevisited.blogspot.com/2014/07/top-50-java-multithreading-interview-
questions-answers.html#ixzz3XrIamELp

You go to any Java interview, senior or junior, experience or freshers, you are bound to see couple of
questions from thread, concurrency and multi-threading. In fact this built-in concurrency support is one
of the strongest point of Java programming language and helped it to gain popularity among enterprise
world and programmers equally. Most of lucrative Java developer position demands excellent core Java
multi-threading skills and experience on developing, debugging and tuning high performance low latency
concurrent Java applications. This is the reason, it is one of the most sought after skill on interviews. In a
typical Java interview, Interviewer slowly starts from basic concepts of Thread by asking questions like,
why you need threads, how to create threads, which one is better way to create threads e.g.
by extending thread class or implementing Runnable and then slowly goes into Concurrency issues,
challenges faced during development of concurrent Java applications, Java memory model, higher order
concurrency utilities introduced in JDK 1.5, principles and design patterns of concurrent Java
applications, classical multi-threading problems e.g. producer consumer, dining philosopher, reader
writer or simply bounded buffer problems. Since its not enough just to know basics of threading, you
must know how to deal with concurrency problems e.g. deadlock, race conditions, memory
inconsistency and various thread safety related issues. These skills are thoroughly get tested by
presenting various multi-threading and concurrency problems. Many Java developers are used to only
look and read interview questions before going for interview, which is not bad but you should not be too
far away. Also collecting questions and going through same exercise is too much time consuming, that's
why I have created this list of top 50 Java multi-threading and concurrency related questions, collected
from various interviews. I am only going to add new and recent interview questions as and when I am
going to discover them. By the way, I have not provided answers of this questions here, Why? because I
expect most of Java developer to know the answers of this question and if not, also answers are widely
available by using Google. If you don't find answer of any particular question, you can always ask me in
comments section. You can even find answers of few questions on the link provided or my earlier
post Top 12 Java Thread Questions with Answers.

50 Interview questions from Java Multi-threading and Concurrency


Here is our list of top questions from Java thread, concurrency and multi-threading. You can use this list
to prepare well for your Java interview.

1) What is Thread in Java?


Thread is an independent path of execution. It's way to take advantage of multiple CPU available in a
machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread
takes 100 millisecond to do a job, you can use 10 thread to reduce that task into 10 millisecond. Java
provides excellent support for multi-threading at language level, and its also one of strong selling point.
For more details see here

2) Difference between Thread and Process in Java?


Thread is subset of Process, in other words one process can contain multiple threads. Two process runs
on different memory space, but all threads share same memory space. Don't confuse this with stack
memory, which is different for different thread and used to store local data to that thread. For more
detail see this answer.

3) How do you implement Thread in Java?


At language level, there are two ways to implement Thread in Java. An instance of
java.lang.Thread represent a thread but it need a task to execute, which is instance of
interface java.lang.Runnable. Since Thread class itself implement Runnable, you can
override run() method either by extending Thread class or just implementing Runnable interface. For
detailed answer and discussion see this article.

4) When to use Runnable vs Thread in Java?


This is follow-up of previous multi-threading interview question. As we know we can implement thread
either by extending Thread class or implementing Runnable interface, question arise, which one is
better and when to use one? This question will be easy to answer, if you know that Java programming
language doesn't support multiple inheritance of class, but it allows you to implement multiple interface.
Which means, its better to implement Runnable than extends Thread, if you also want to extend
another class e.g. Canvas or CommandListener. For more points and discussion you can also refer
this post.

6) Difference between start() and run() method of Thread class?


One of trick Java question from early days, but still good enough to differentiate between shallow
understanding of Java threading model start() method is used to start newly created thread, while
start() internally calls run() method, there is difference calling run() method directly. When you
invoke run() as normal method, its called in the same thread, no new thread is started, which is the
case when you call start() method. Read this answer for much more detailed discussion.

7) Difference between Runnable and Callable in Java?


Both Runnable and Callable represent task which is intended to be executed in separate thread.
Runnable is there from JDK 1.0, while Callable was added on JDK 1.5. Main difference between these
two is that Callable's call() method can return value and throw Exception, which was not possible
with Runnable's run() method. Callable return Future object, which can hold result of computation.
See my blog post on same topic for more in-depth answer of this question.

8) Difference between CyclicBarrier and CountDownLatch in Java?


Though both CyclicBarrier and CountDownLatch wait for number of threads on one or more events,
main difference between them is that you can not re-use CountDownLatch once count reaches to
zero, but you can reuse same CyclicBarrier even after barrier is broken. See this answer for few
more points and sample code example.

9) What is Java Memory model?


Java Memory model is set of rules and guidelines which allows Java programs to behave deterministically
across multiple memory architecture, CPU, and operating system. It's particularly important in case of
multi-threading. Java Memory Model provides some guarantee on which changes made by one thread
should be visible to others, one of them is happens-before relationship. This relationship defines several
rules which allows programmers to anticipate and reason behaviour of concurrent Java programs. For
example, happens-before relationship guarantees :

 Each action in a thread happens-before every action in that thread that comes later in the
program order, this is known as program order rule.
 An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock,
also known as Monitor lock rule.

 A write to a volatile field happens-before every subsequent read of that same field, known as
Volatile variable rule.

 A call to Thread.start on a thread happens-before any other thread detects that thread has
terminated, either by successfully return from Thread.join() or by Thread.isAlive()
returning false, also known as Thread start rule.

 A thread calling interrupt on another thread happens-before the interrupted thread detects the
interrupt( either by having InterruptedException thrown, or invoking isInterrupted or
interrupted), popularly known as Thread Interruption rule.

 The end of a constructor for an object happens-before the start of the finalizer for that object,
known as Finalizer rule.

 If A happens-before B, and B happens-before C, then A happens-before C, which means


happens-before guarantees Transitivity.

I strongly suggest to read Chapter 16 of Java Concurrency in Practice to understand Java Memory model
in more detail.
10) What is volatile variable in Java?
volatile is a special modifier, which can only be used with instance variables. In concurrent Java
programs, changes made by multiple threads on instance variables is not visible to other in absence of
any synchronizers e.g. synchronized keyword or locks. Volatile variable guarantees that a write will
happen before any subsequent read, as stated "volatile variable rule" in previous question. Read this
answer to learn more about volatile variable and when to use them.

11) What is thread-safety? is Vector a thread-safe class? (Yes, see details)


Thread-safety is a property of an object or code which guarantees that if executed or used by multiple
thread in any manner e.g. read vs write it will behave as expected. For example, a thread-safe counter
object will not miss any count if same instance of that counter is shared among multiple threads.
Apparently, you can also divide collection classes in two category, thread-safe and non-thread-safe.
Vector is indeed a thread-safe class and it achieves thread-safety by synchronizing methods which
modifies state of Vector, on the other hand, its counterpart ArrayList is not thread-safe.

12) What is race condition in Java? Given one example?


Race condition are cause of some subtle programming bugs when Java programs are exposed to
concurrent execution environment. As name suggests, race condition occurs due to race between
multiple threads, if a thread which is supposed to execute first lost the race and executed second,
behaviour of code changes, which surface as non-deterministic bugs. This is one of the hardest bugs to
find and re-produce because of random nature of racing between threads. One example of race
condition is out-of-order processing, see this answer for some more example of race conditions in
Java programs.

13) How to stop thread in Java?


I always said that Java provides rich APIs for everything but ironically Java doesn't provide a sure shot
way of stopping thread. There was some control methods in JDK 1.0 e.g. stop(), suspend() and
resume() which was deprecated in later releases due to potential deadlock threats, from then Java API
designers has not made any effort to provide a consistent, thread-safe and elegant way to stop threads.
Programmers mainly rely on the fact that thread stops automatically as soon as they finish execution of
run() or call() method. To manually stop, programmers either take advantage of volatile boolean
variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel
tasks. See this tutorial for sample code of stopping thread in Java.

14) What happens when an Exception occurs in a thread?


This is one of the good tricky Java question I have seen on interviews. In simple words, If not caught
thread will die, if an uncaught exception handler is registered then it will get a call back.
Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers
invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to
terminate due to an uncaught exception the Java Virtual Machine will query the thread for its
UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will
invoke the handler's uncaughtException() method, passing the thread and the exception as
arguments.

15) How do you share data between two thread in Java?


You can share data between threads by using shared object, or concurrent data-structure like
BlockingQueue. See this tutorial to learn inter thread communication in Java. It implements Producer
consumer pattern using wait and notify methods, which involves sharing objects between two threads.

16) Difference between notify and notifyAll in Java?


This is another tricky questions from core Java interviews, since multiple threads can wait on single
monitor lock, Java API designer provides method to inform only one of them or all of them, once waiting
condition changes, but they provide half implementation. There notify() method doesn't provide
any way to choose a particular thread, that's why its only useful when you know that there is only one
thread is waiting. On the other hand, notifyAll() sends notification to all threads and allows them
to compete for locks, which ensures that at-least one thread will proceed further. See my blog post on
similar topic for more detailed answer and code example.

17) Why wait, notify and notifyAll are not inside thread class?
This is a design related question, which checks what candidate thinks about existing system or does he
ever thought of something which is so common but looks in-appropriate at first. In order to answer this
question, you have to give some reasons why it make sense for these three method to be in Object class,
and why not on Thread class. One reason which is obvious is that Java provides lock at object level not at
thread level. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain
lock it make sense to call wait() on that object rather than on that thread. Had wait() method
declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait,
notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs
to object. You can also see this article for more elaborate answer of this question.

18) What is ThreadLocal variable in Java?


ThreadLocal variables are special kind of variable available to Java programmer. Just like instance variable
is per instance, ThreadLocal variable is per thread. It's a nice way to achieve thread-safety of
expensive-to-create objects, for example you can make SimpleDateFormat thread-safe using
ThreadLocal. Since that class is expensive, its not good to use it in local scope, which requires
separate instance on each invocation. By providing each thread their own copy, you shoot two birds in
one arrow. First, you reduce number of instance of expensive object by reusing fixed number of
instances, and Second, you achieve thread-safety without paying cost of synchronization or immutability.
Another good example of thread local variable is ThreadLocalRandom class, which reduces number
of instances of expensive-to-create Random object in multi-threading environment. See this
answer to learn more about thread local variables in Java.

19) What is FutureTask in Java?


FutureTask represents a cancellable asynchronous computation in concurrent Java application. This
class provides a base implementation of Future, with methods to start and cancel a computation, query
to see if the computation is complete, and retrieve the result of the computation. The result can only be
retrieved when the computation has completed; the get methods will block if the computation has not
yet completed. A FutureTask object can be used to wrap a Callable or Runnable object. Since
FutureTask also implements Runnable, it can be submitted to an Executor for execution.

20) Difference between interrupted and isInterrupted method in Java?


Main difference between interrupted() and isInterrupted() is that former clears the
interrupt status while later does not. The interrupt mechanism in Java multi-threading is implemented
using an internal flag known as the interrupt status. Interrupting a thread by calling
Thread.interrupt() sets this flag. When interrupted thread checks for an interrupt by invoking
the static method Thread.interrupted(), interrupt status is cleared. The non-static
isInterrupted() method, which is used by one thread to query the interrupt status of another,
does not change the interrupt status flag. By convention, any method that exits by throwing an
InterruptedException clears interrupt status when it does so. However, it's always possible that
interrupt status will immediately be set again, by another thread invoking interrupt

21) Why wait and notify method are called from synchronized block?
Main reason for calling wait and notify method from either synchronized block or method is that it made
mandatory by Java API. If you don't call them from synchronized context, your code will throw
IllegalMonitorStateException. A more subtle reason is to avoid race condition between wait
and notify calls. To learn more about this, check my similarly titled post here.

22) Why you should check condition for waiting in a loop?


Its possible for a waiting thread to receive false alerts and spurious wake up calls, if it doesn't check the
waiting condition in loop, it will simply exit even if condition is not met. As such, when a waiting thread
wakes up, it cannot assume that the state it was waiting for is still valid. It may have been valid in the
past, but the state may have been changed after the notify() method was called and before the
waiting thread woke up. That's why it always better to call wait() method from loop, you can even create
template for calling wait and notify in Eclipse. To learn more about this question, I would recommend
you to read Effective Java items on thread and synchronization.

23) Difference between synchronized and concurrent collection in Java?


Though both synchronized and concurrent collection provides thread-safe collection suitable for multi-
threaded and concurrent access, later is more scalable than former. Before Java 1.5, Java programmers
only had synchronized collection which becomes source of contention if multiple thread access them
concurrently, which hampers scalability of system. Java 5 introduced concurrent collections like
ConcurrentHashMap, which not only provides thread-safety but also improves scalability by using
modern techniques like lock stripping and partitioning internal table. See this answer for more
differences between synchronized and concurrent collection in Java.

24) Difference between Stack and Heap in Java?


Why do someone this question as part of multi-threading and concurrency? because Stack is a memory
area which is closely associated with threads. To answer this question, both stack and heap are specific
memories in Java application. Each thread has their own stack, which is used to store local variables,
method parameters and call stack. Variable stored in one Thread's stack is not visible to other. On other
hand, heap is a common memory area which is shared by all threads. Objects whether local or at any
level is created inside heap. To improve performance thread tends to cache values from heap into their
stack, which can create problems if that variable is modified by more than one thread, this is where
volatile variables comes in picture. volatile suggest threads to read value of variable always from main
memory. See this article to learn more about stack and heap in Java to answer this question in greater
detail.

25) What is thread pool? Why should you thread pool in Java?
Creating thread is expensive in terms of time and resource. If you create thread at time of request
processing it will slow down your response time, also there is only a limited number of threads a process
can create. To avoid both of these issue, a pool of thread is created when application starts-up and
threads are reused for request processing. This pool of thread is known as "thread pool" and threads are
known as worker thread. From JDK 1.5 release, Java API provides Executor framework, which allows you
to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed
thread pool (a pool of fixed number of thread) or cached thread pool (an expandable thread pool
suitable for applications with many short lived tasks). See this article to learn more about thread pools in
Java to prepare detailed answer of this question.
26) Write code to solve Producer Consumer problem in Java?
Most of the threading problem you solved in real world are of category of Producer consumer pattern,
where one thread is producing task and other thread is consuming that. You must know how to do inter
thread communication to solve this problem. At lowest level, you can use wait and notify to solve this
problem, and at high level you can leverage Semaphore or BlockingQueue to implement Producer
consumer pattern, as shown in this tutorial.

27) How do you avoid deadlock in Java? Write Code?

Deadlock is a condition in which two threads wait for each other to take action which allows them to
move further. It's a serious issue because when it happen your program hangs and doesn't do the task it
is intended for. In order for deadlock to happen, following four condition must be true :

 Mutual Exclusion : At least one resource must be held in a non-shareable mode. Only one
process can use the resource at any given instant of time.
 Hold and Wait : A process is currently holding at least one resource and requesting additional
resources which are being held by other processes.

 No Pre-emption : The operating system must not de-allocate resources once they have been
allocated; they must be released by the holding process voluntarily.

 Circular Wait : A process must be waiting for a resource which is being held by another process,
which in turn is waiting for the first process to release the resource.
Easiest way to avoid deadlock is to prevent Circular wait, and this can be done by acquiring locks in a
particular order and releasing them in reverse order, so that a thread can only proceed to acquire a lock
if it held the other one. Check this tutorial for actual code example and detailed discussion
on techniques of avoiding deadlock in Java.

28) Difference between livelock and deadlock in Java?


This question is extension of previous interview question. A livelock is similar to a deadlock, except that
the states of the threads or processes involved in the livelock constantly change with regard to one
another, without any one progressing further. Livelock is a special case of resource starvation. A real-
world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite
by moving aside to let the other pass, but they end up swaying from side to side without making any
progress because they both repeatedly move the same way at the same time. In short, main difference
between livelock and deadlock is that in former state of process change but no progress is made.

29) How do you check if a Thread holds a lock or not?


I didn't even know that you can check if a Thread already holds lock before this question hits me in a
telephonic round of Java interview. There is a method called holdsLock() on java.lang.Thread,
it returns true if and only if the current thread holds the monitor lock on the specified object. You can
also check this article for more detailed answer.

30) How do you take thread dump in Java?


There are multiple ways to take thread dump of Java process depending upon operating system. When
you take thread dump, JVM dumps state of all threads in log files or standard error console. In windows
you can use Ctrl + Break key combination to take thread dump, on Linux you can use kill -3
command for same. You can also use a tool called jstack for taking thread dump, it operate on
process id, which can be found using another tool called jps.

31) Which JVM parameter is used to control stack size of thread?


This is the simple one, -Xss parameter is used to control stack size of Thread in Java. You can see this list
of JVM options to learn more about this parameter.

32) Difference between synchronized and ReentrantLock in Java?


There were days when only way to provide mutual exclusion in Java was via synchronized keyword, but it
has several shortcomings e.g. you can not extend lock beyond a method or block boundary, you can not
give up trying for a lock etc. Java 5 solves this problem by providing more sophisticated control via Lock
interface. ReentrantLock is a common implementation of Lock interface and provides re-entrant mutual
exclusion Lock with the same basic behaviour and semantics as the implicit monitor lock accessed using
synchronized methods and statements, but with extended capabilities. See this article to learn about
those capabilities and some more differences between synchronized vs ReentrantLock in Java.

33) There are three threads T1, T2 and T3? How do you ensure sequence T1, T2, T3 in Java? Sequencing
in multi-threading can be achieved by different means but you can simply use join() method of thread
class to start a thread when another one is finished its execution. To ensure three threads execute you
need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join,
and T2 calls T1.join, this ways T1 will finish first and T3 will finish last. To learn more about join method,
see this tutorial.

34) What does yield method of Thread class do?


Yield method is one way to request current thread to relinquish CPU so that other thread can get chance
to execute. Yield is a static method and only guarantees that current thread will relinquish the CPU but
doesn't say anything about which other thread will get CPU. Its possible for same thread to get CPU back
and start its execution again. See this article to learn more about yield method and to answer this
question better.

35) What is concurrence level of ConcurrentHashMap in Java?


ConcurrentHashMap achieves it's scalability and thread-safety by partitioning actual map into number of
sections. This partitioning is achieved using concurrency level. It's optional parameter of
ConcurrentHashMap constructor and it's default value is 16. The table is internally partitioned to try to
permit the indicated number of concurrent updates without contention. To learn more about
concurrency level and internal resizing, see my post How ConcurrentHashMap works in Java.

36) What is Semaphore in Java?


Semaphore in Java is a new kind of synchronizer. It's a counting semaphore. Conceptually, a semaphore
maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it.
Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects
are used; the Semaphore just keeps a count of the number available and acts accordingly. Semaphore is
used to protect expensive resource which is available in fixed number e.g. database connection in pool.
See this article to learn more about counting Semaphore in Java.

37) What happens if you submit task, when queue of thread pool is already fill?
This is another tricky question in my list. Many programmer will think that it will block until a task is
cleared but its true. ThreadPoolExecutor's submit() method throws
RejectedExecutionException if the task cannot be scheduled for execution.

38) Difference between submit() and execute() method thread pool in Java?
Both method are ways to submit task to thread pools but there is slight difference between them.
execute(Runnable command) is defined in Executor interface and executes given task in future, but more
importantly it does not return anything. It's return type is void. On other hand submit() is overloaded
method, it can take either Runnable or Callable task and can return Future object which can hold
pending result of computation. This method is defined on ExecutorService interface, which
extends Executor interface, and every other thread pool class e.g. ThreadPoolExecutor or
ScheduledThreadPoolExecutor gets these methods. To learn more about thread pools you can
check this article.

39) What is blocking method in Java?


A blocking method is a method which blocks until task is done, for example accept() method of
ServerSocket blocks until a client is connected. here blocking means control will not return to caller until
task is finished. On the other hand there are asynchronous or non-blocking method which returns even
before task is finished. To learn more about blocking method see this answer.

40) Is Swing thread-safe? What do you mean by Swing thread-safe?


You can simply this question as No, Swing is not thread-safe, but you have to explain what you mean by
that even if interviewer doesn't ask about it. When we say swing is not thread-safe we usually refer its
component, which can not be modified in multiple threads. All update to GUI components has to be
done on AWT thread, and Swing provides synchronous and asynchronous callback methods to schedule
such updates. You can also read my article to learn more about swing and thread-safety to better answer
this question. Even next two questions are also related to this concept.

41) Difference between invokeAndWait and invokeLater in Java?


These are two methods Swing API provides Java developers to update GUI components from threads
other than Event dispatcher thread. InvokeAndWait() synchronously update GUI component, for
example a progress bar, once progress is made, bar should also be updated to reflect that change. If
progress is tracked in a different thread, it has to call invokeAndWait() to schedule an update of
that component by Event dispatcher thread. On other hand, invokeLater() is asynchronous call to
update components. You can also refer this answer for more points.

42) Which method of Swing API are thread-safe in Java?


This question is again related to swing and thread-safety, though components are not thread-safe there
are certain method which can be safely call from multiple threads. I know about repaint(), and
revalidate() being thread-safe but there are other methods on different swing components e.g.
setText() method of JTextComponent, insert() and append() method of JTextArea
class.

43) How to create Immutable object in Java?


This question might not look related to multi-threading and concurrency, but it is. Immutability helps to
simplify already complex concurrent code in Java. Since immutable object can be shared without any
synchronization its very dear to Java developers. Core value object, which is meant to be shared among
thread should be immutable for performance and simplicity. Unfortunately there is no @Immutable
annotation in Java, which can make your object immutable, hard work must be done by Java developers.
You need to keep basics like initializing state in constructor, no setter methods, no leaking of reference,
keeping separate copy of mutable object to create Immutable object. For step by step guide see my post,
how to make an object Immutable in Java. This will give you enough material to answer this question
with confidence.

44) What is ReadWriteLock in Java?


In general, read write lock is result of lock stripping technique to improve performance of concurrent
applications. In Java, ReadWriteLock is an interface which was added in Java 5
release. A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one
for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no
writers. The write lock is exclusive. If you want you can implement this interface with your own set of
rules, otherwise you can use ReentrantReadWriteLock, which comes along with JDK and supports
a maximum of 65535 recursive write locks and 65535 read locks.

45) What is busy spin in multi-threading?


Busy spin is a technique which concurrent programmers employ to make a thread wait on certain
condition. Unlike traditional methods e.g. wait(), sleep() or yield() which all involves relinquishing CPU
control, this method does not relinquish CPU, instead it just runs empty loop. Why would someone do
that? to preserve CPU caches. In multi core system, its possible for a paused thread to resume on
different core, which means rebuilding cache again. To avoid cost of rebuilding cache, programmer prefer
to wait for much smaller time doing busy spin. You can also see this answer to learn more about this
question.

46) Difference between volatile and atomic variable in Java?


This is an interesting question for Java programmer, at first, volatile and atomic variable look very similar,
but they are different. Volatile variable provides you happens-before guarantee that a write will happen
before any subsequent write, it doesn't guarantee atomicity. For example count++ operation will not
become atomic just by declaring count variable as volatile. On the other hand AtomicInteger class
provides atomic method to perform such compound operation atomically e.g. getAndIncrement()
is atomic replacement of increment operator. It can be used to atomically increment current value by
one. Similarly you have atomic version for other data type and reference variable as well.

47) What happens if a thread throws an Exception inside synchronized block?


This is one more tricky question for average Java programmer, if he can bring the fact about whether lock
is released or not is key indicator of his understanding. To answer this question, no matter how you exist
synchronized block, either normally by finishing execution or abruptly by throwing exception, thread
releases the lock it acquired while entering that synchronized block. This is actually one of the reason I
like synchronized block over lock interface, which requires explicit attention to release lock, generally this
is achieved by releasing lock in finally block.

48) What is double checked locking of Singleton?


This is one of the very popular question on Java interviews, and despite its popularity, chances of
candidate answering this question satisfactory is only 50%. Half of the time, they failed to write code for
double checked locking and half of the time they failed how it was broken and fixed on Java 1.5. This is
actually an old way of creating thread-safe singleton, which tries to optimize performance by only
locking when Singleton instance is created first time, but because of complexity and the fact it was
broken for JDK 1.4, I personally don't like it. Anyway, even if you not prefer this approach its good to
know from interview point of view. Since this question deserve a detailed answer, I have answered in a
separate post, you can read my post how double checked locking on Singleton works to learn more
about it.

49) How to create thread-safe Singleton in Java?


This question is actually follow-up of previous question. If you say you don't like double checked locking
then Interviewer is bound to ask about alternative ways of creating thread-safe Singleton class. There are
actually man, you can take advantage of class loading and static variable initialization feature of JVM to
create instance of Singleton, or you can leverage powerful enumeration type in Java to create Singleton. I
actually preferred that way, you can also read this article to learn more about it and see some sample
code.

50) List down 3 multi-threading best practice you follow?


This is my favourite question, because I believe that you must follow certain best practices while writing
concurrent code which helps in performance, debugging and maintenance. Following are three best
practices, I think an average Java programmer should follow :
 Always give meaningful name to your threadThis goes a long way to find a bug or trace an
execution in concurrent code. OrderProcessor, QuoteProcessor or
TradeProcessor is much better than Thread-1. Thread-2 and Thread-3. Name should say
about task done by that thread. All major framework and even JDK follow this best practice.
 Avoid locking or Reduce scope of Synchronization
Locking is costly and context switching is even more costlier. Try to avoid synchronization and
locking as much as possible and at bare minimum, you should reduce critical section. That's why
I prefer synchronized block over synchronized method, because it gives you absolute control on
scope of locking.

 Prefer Synchronizers over wait and notify


Synchronizers like CountDownLatch, Semaphore, CyclicBarrier or Exchanger
simplifies coding. It's very difficult to implement complex control flow right using wait and notify.
Secondly, these classes are written and maintained by best in business and there is good chance
that they are optimized or replaced by better performance code in subsequent JDK releases. By
using higher level synchronization utilities, you automatically get all these benefits.

 Prefer Concurrent Collection over Synchronized Collection


This is another simple best practice which is easy to follow but reap good benefits. Concurrent
collection are more scalable than their synchronized counterpart, that's why its better to use
them while writing concurrent code. So next time if you need map, think about
ConcurrentHashMap before thinking Hashtable. See my article Concurrent Collections in
Java, to learn more about modern collection classes and how to make best use of them.

51) How do you force start a Thread in Java?


This question is like how do you force garbage collection in Java, their is no way, though you can make
request using System.gc() but its not guaranteed. On Java multi-threading their is absolute no way
to force start a thread, this is controlled by thread scheduler and Java exposes no API to control thread
schedule. This is still a random bit in Java.

52) What is fork join framework in Java?


The fork join framework, introduced in JDK 7 is a powerful tool available to Java developer to take
advantage of multiple processors of modern day servers. It is designed for work that can be broken into
smaller pieces recursively. The goal is to use all the available processing power to enhance the
performance of your application. One significant advantage of The fork/join framework is that it
uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other
threads that are still busy. See this article for much more detailed answer of this question.

53) What is difference between calling wait() and sleep() method in Java multi-threading?
Though both wait and sleep introduce some form of pause in Java application, they are tool for different
needs. Wait method is used for inter thread communication, it relinquish lock if waiting condition is true
and wait for notification when due to action of another thread waiting condition becomes false. On the
other hand sleep() method is just to relinquish CPU or stop execution of current thread for specified
time duration. Calling sleep method doesn't release the lock held by current thread. You can also take
look at this article to answer this question with more details.

That's all on this list of top 50 Java multi-threading and concurrency interview questions. I have not
shared answers of all the questions but provided enough hints and links to explore further and find
answers by yourselves. As I said, let me know if you don't find answer of any particular question and I
will add answer here. You can use this list to not only to prepare for your core Java and programming
interviews but also to check your knowledge about basics of threads, multi-threading, concurrency,
design patterns and threading issues like race conditions, deadlock and thread safety problems. My
intention is to make this list of question as mother of all list of Java Multi-threading questions, but this
can not be done without your help. You can also share any question with us, which has been asked to
you or any question for which you yet to find an answer. This master list is equally useful to Java
developers of all levels of experience. You can read through this list even if you have 2 to 3 years of
working experience as junior developer or 5 to 6 years as senior developer. It's even useful for freshers
and beginners to expand their knowledge. I will add new and latest multi-threading question as and
when I come across, and I request you all to ask, share and answer questions via comments to keep this
list relevant for all Java programmers.

You might like:


 What is Race Condition in multithreading – 2 Examples in Java
 How to Implement Thread in Java with Example

 Why wait notify and notifyAll called from synchronized block or method in Java

 How to Join Multiple Threads in Java - Thread Join Example

Read more: http://javarevisited.blogspot.com/2014/07/top-50-java-multithreading-interview-questions-


answers.html#ixzz3XrJ9HGaZ

Comments/ques:

One questions I found interesting from threads was , what is difference between
interrupt(), isInterrupted() and interrupted()? first one interrupt the thread on which object
it was called, second is called from the thread which was interrupted and return true if it
was indeed interrupted, otherwise false. The last one clear the interrupted status of thread.
Read more: http://javarevisited.blogspot.com/2014/07/top-50-java-multithreading-interview-
questions-answers.html#ixzz3XrKlRTip

Top 15 Java Multithreading, Concurrency


Interview Questions Answers asked in
Investment banks
Read more: http://javarevisited.blogspot.com/2011/07/java-multi-threading-
interview.html#ixzz3XrisoYaY
Thread interview questions Java

Multi-threading and concurrency questions are essential part of any Java interview. If you are going for any Java

interview on any Investment bank for equities front office position expect lots of muti-threading interview

questions on your way. Multi-threading and concurrency is a favorite topics on Investment banking specially
on electronic trading development and they grill candidate on many confusing java thread interview questions. They
just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java
because most of them are in business of performance. High volume and low latency Electronic trading System which
is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview
questions on Java asked on different on different time. I am not providing answer of these thread interview questions
but I will give you hint whenever possible, some time hint is enough to answer. I will update the post further with
detailed answers just like I did for 10 Singleton interview questions in Java recently. With introduction of concurrency
package in Java 5 questions on concurrent utility and concurrent collections are on rise as well. ThreadLocal,
BlockingQueue, Counting Semaphore and ConcurrentHashMap are popular among those.

15 Java Thread Interview Questions and answers


1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?

This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of
this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of
this multi-threading questions is simple it can be achieved by using join method of Thread class.

2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a
high performance cache which allows multiple reader but single writer to keep the integrity how will you
implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate
lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and
conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up
questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any
java multi-threading interview because now days Its heavily used to build cache for electronic trading system on
client and exchange connectivity space.

3) What are differences between wait and sleep method in java?

Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is
wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-
thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for
more differences

4) Write code to implement blocking queue in Java?

This is relatively tough java multi-threading interview question which servers many purpose, it checks whether
candidate can actually write Java code using thread or not, it sees how good candidate is on understanding
concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and
notify() method to implement blocking queue, Once interviewee successfully writes it you can ask him to write it
again using new java 5 concurrent classes etc.

5) Write code to solve the Produce consumer problem in Java?

Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How
do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to
solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even
ask to implement solution of dining philosopher problem as well.

6) Write a program which will result in deadlock? How will you fix deadlock in Java?

This is my favorite java thread interview question because even though deadlock is quite common while writing
multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle.
Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can
be replace with 2 for simplest case and higher number to make question more intimidating. see How to avoid
deadlock in java for more information on deadlock in Java.
7) What is atomic operation? What are atomic operations in Java?

Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You
can read more about java synchronization here.

8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?

Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5
and Java memory model. It’s good to prepare well about how volatile variables ensures visibility, ordering and
consistency in concurrent environment.

9) What is race condition? How will you find and solve race condition?

Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on
recent race condition you have faced and how did you solve it and some time they will write sample code and ask you
detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the
best java thread interview question and can really test the candidate's experience on solving race condition or writing
code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency
practices in Java'".

10) How will you take thread dump in Java? How will you analyze Thread dump?

In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather
simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful
to analyze deadlock situations as well.

11) Why we call start() method which in turns calls run() method, why not we directly call run()
method ?

Another classic java multi-threading interview question This was my original doubt when I started programming in
thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews.
Answer to this question is that, when you call start() method it creates new Thread and execute code declared in
run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread.
Read my post Difference between start and run method in Thread for more details.
12) How will you awake a blocked thread in java?

This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think
there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of
calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing
InterruptedException. See my post How to deal with blocking methods in Java for more information on handling
blocked thread.

13) What is difference between CyclicBarriar and CountdownLatch in Java ?

New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages. One difference is
that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch.

14) What is immutable object? How does it help on writing concurrent application?

Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This
java interview question can become more tricky if ask you to write an immutable class or ask you Why String is
immutable in Java as follow-up.

15) What are some common problems you have faced in multi-threading environment? How did you resolve
it?

Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in
multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to
detect and debug. This is mostly experienced based interview question on java thread instead of fact based.

These were my favorite Java thread interview questions and mostly asked on Investment banks. This list is by no
means complete so please contribute some of interesting java thread questions you have faced during interview.
Purpose of this article is to collect and share great interview questions on multi-threading concept which not only
helps on interview but opens door for learning new threading concept.

Update:
One of Javarevisited reader, Hemant has contributed some more thread interview questions in Java, though he hasn’t
provide answer and left that job for me, I will certainly do when time allows, just like I have recently updated 10
Singleton interview question in Java with answers. If you guys know answers of this java concurrency questions than
please post as comment:

Here is his comment “Good questions on multi-threading though you may need to prepare more in order to clear any
multi-threading interview, you need to be familiar with concept of immutability, thread-safety, race condition and many
more. 10 or 15 question is good for quick recap but you at-least need to prepare more than 50 questions on threading
and concurrency to perform better on Java interview. You can find some interesting thread question below which is no
doubt highly popular –

1) Difference between green thread and native thread in Java?

2) Difference between thread and process?

3) What is context switching in multi-threading?

4) Difference between deadlock and livelock, deadlock and starvation?

5) What thread-scheduling algorithm is used in Java?

6) What is thread-scheduler in Java?

7) How do you handle un-handled exception in thread?

8) What is thread-group, why its advised not to use thread-group in Java?

9) Why Executor framework is better than creating and managing thread by


application ?

10) Difference between Executor and Executors in Java?

10) How to find which thread is taking maximum cpu in windows and Linux server?

Apart from practicing these question answers, more important is to understand the concept behind these multi-
threading questions simply mugging the answers of these thread interview questions is not going to help because
there would be a lot of follow-ups based upon your answer and if you haven't master the particular thread topic it
would be difficult to answer them.

Related post:

Why wait, notify and notifyAll are defined in Object class in Java?

Difference between Runnable and Thread in Java

Why wait and notify needs to be called from synchronized method?

invokeAndWait vs invokeLater in Java Swing


Why you should not mix static and non static synchronized method in Java

How to stop Thread in Java

You might like:

 Difference between Wait and Sleep , Yield in Java


 Java Synchronization Tutorial : What, How and Why?

 Producer Consumer Design Pattern with Blocking Queue Example in Java

 Top 10 Java Serialization Interview Questions and Answers

Recommended by
Posted by Javin Paul at 6:08 AM

Email This BlogThis! Share to Twitter Share to Facebook

Labels: core java , core java interview question

Location: United States

28 comments :
Anonymous said...

Indeed a great collection of java multi-threading interview questions and I agree with
you. wall street firms really need people who are very strong in multi-threading and
concurrent programming. you could probably include more interview questions from new
Thread classes added on JDK5

July 28, 2011 at 9:50 PM

Anonymous said...

answers of your thread interview questions are not proper. you should work to make your
interview questions and answers more relevant, accurate and better. Though I agree that
multi-threading is not an easy thing to achieve and multi-threading interview is real
tough.

August 4, 2011 at 11:33 PM

Anonymous said...

Thanks for another great post! You're very smart, and you're writing really important
articles. That being said, you have to get an editor! Your spelling, grammar, and
punctuation distract from otherwise amazing content. Writing is a great way to get better
at writing, but you can get better even faster with feedback from writers with more skill
than yourself. In any case, you rock and have amazing potential.
September 23, 2011 at 9:03 AM

Javin@ OutOfMemoryError in Java said...

@Anonymous, thanks for your feedback , English not being my first language, it has
some characteristic or effect of Hindi in grammar and work flow.I love to make my
English flawless and increase reading experience of my readers but more importantly I
like to share my experience and until I connect to my readers or my fellow developers I
am happy and it motivates me to improve. Once again thanks for your feedback
appreciate.

Javin

September 23, 2011 at 6:26 PM

Javin @ OutOfMemoryError in Perm Gen Space said...

Hi Vineet, its indeed a interview question guide, you can easily find detailed answer for
these multi-threading question by doing google, Though I have also provided pointers
and main point which some one will look. would be great if you could contribute some
good answer and I will include in post.

October 14, 2011 at 6:12 PM

Anonymous said...

Usage of Singleton Pattern in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()

November 9, 2011 at 11:16 AM

Garima said...

I am looking for some more thread questions and answers in Java, your thread questions
are good but I need more tough thread interview questions something which is new and
not everybody know about those interview questions.Please help

November 23, 2011 at 2:27 AM

Anonymous said...

Question: what are the benfits we will get when we extend a java.lang.Thread class
instead of implimenting Runnable interface?

January 11, 2012 at 5:12 AM


Arulkumaran.K said...

Good list of questions. I have listed frequently asked multi-threading interview questions
and answers at http://java-success.blogspot.com.au/2011/09/java-multi-threading-
interview.html that will be very handy as well.

February 26, 2012 at 10:07 PM

Javin @ spring interview question answer said...

Thanks Arul. you like these thread interview questions. glad to here that.

February 27, 2012 at 5:36 AM

Javin @ Servelt Interview Questions said...

Thanks Kamal. I have shared many of those in my blog, just use search box on top left.
by the way here are few :
10 questions on Singleton Pattern in Java
Why String is immutable in Java

March 23, 2012 at 7:10 AM

Peter Lawrey said...

1. I would call run() instead of start() ;)

2. I would make it clear there is a difference between ReentrantLock and


ReentrantReadWriteLock.

4. While I started programming Java before version 5.0, many people started
programming after 2004, so I wouldn't consider the concurrency library that new as there
when many people started. BTW It was available as a separate library from 1998

6. My favourite answer to this is to create a Thread in a static block which access the
class and does a join. This creates a deadlock with just one new thread and no explicit
locking. ;)

8. Another question I get is the difference in volatile between Java and C++

10. You might add, how do you take a thread dump programmatically.

Excellent posts, keep them up.

April 8, 2012 at 12:50 AM

Javin @ thread safe class in java said...


Hi Peter, Good to see you back here :) difference between volatile in Java and C++ is a
good question if you mention C++ in your resume and also taking a thread dump
programmatically and with command prompt in case of deadlock is a good skill to have.
What is current trend, have you spotted any new trend related to concurrency in Java
interviews ?

April 9, 2012 at 6:10 AM

Anonymous said...

Can you please share some multi-threading questions asked in Google Interviews. I am
very interested on what these top companies like Google, Amazon, Facebook or
Investment banks like Nomura or Goldman asked in Java, JVM and Threading. Thanks

April 10, 2012 at 8:02 PM

Jon said...

Is it possible that interviewers do not always know the answers, and are taking advantage
of job interviews to get free software consultancy?

July 21, 2012 at 5:15 AM

Javin @ transient vs volatile said...

@Jon, You bring the very interesting point about Java interviews,Many do and which I
guess is not bad because if some one can solve the problem you are facing than it's good
signal that guy can be useful.

July 21, 2012 at 5:21 AM

Anonymous said...

Please try to answer question dont leave reader in dark room

August 28, 2012 at 12:10 AM

Anonymous said...

Javin, really good questions. Just another query which core java book you recommned to
understand concepts.

December 4, 2012 at 11:53 PM

mayank tripathi said...


@Javin : The main advantage of new Locks over Synchronized block is to handle
Deadlock better way. In blocks once deadlock happens you have no way to fix it unless
restart the jvm but Lock gives you tools to handle deadlock situations. Other benefits are
bonus :)

February 11, 2013 at 4:09 PM

Rashi said...

Hi Guys, I would like to share one of the Interview Question related to ThreadPool
implementation. I was asked in JP Morgan and Chase that , What should you take care, if
you have to make your own Thread Pool? I thought about Executors framework of Java 5
but couldn't answer much. I am interested in points, what are the important points one
should take care while creating there own thread pool in Java?

Thx
Rashi

April 16, 2013 at 8:52 PM

Anonymous said...

I was asked to implement thread pool in java as well and they were interested in knowing
key things you would consider to design pool

April 26, 2013 at 10:01 PM

Andrew said...

Why knowledge of multithreading in Java is so important to get a Job? What makes it so


desirable and same time tough to get master?

August 12, 2013 at 9:04 PM

Aravind Datta said...

Javin, I am a Java developer with 10+ years of experience and accidentally bumped into
your blog around 15 days ago. Since then, I am stuck with it :-). I tried to read thru so
many articles that you wrote and they are extremely useful and extremely well written
with a lot of clarity on the fundamental concepts! Its a great job! Keep it up!

I have a couple of questions on threads:


1. Is "a thread of execution" same as "thread object" ?
2. Lets say, there is a java application (in real production scenario) and it can accept
concurrent requests.. implies, multiple users can get data from this application while it is
running in production.. and I can see the logs that multiple "threads" are running in the
log.. like say, Thread-1, Thread-2, Thread-23, Thread-50.. etc.. based on the number of
"concurrent" requests it is processing.
My question is, is this concurrency same as "multi threading within an application"? Or is
it different? Can a java application handle concurrent requests (from multiple
users/sessions) simultaneously by default? How does it work? Please let us know.

Best wishes..

September 28, 2013 at 10:28 AM

Sekhar babu Karri said...

package com.learning.material;

public class MyThread {

/**
* @param args
*/
public static void main(String[] args) throws InterruptedException {

System.out.println("i am the Main thread...starting......");

final Thread t1 = new Thread(){


public void run(){
System.out.println("i am thread 1 starting......");
try{
Thread.sleep(5000);
System.out.println("I am Thread 1 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};

final Thread t2 = new Thread(){


public void run(){
try{
t1.join();
System.out.println("I am Thread 2 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};
Thread t3 = new Thread(){
public void run(){
try{
t2.join();
System.out.println("I am Thread 3 finished ");
}catch(InterruptedException ie){
System.out.println("Exception:"+ie.getMessage());
}
}
};
t1.start();
t2.start();
t3.start();
t3.join();

System.out.println("i am Main thread finished");

November 12, 2013 at 10:27 AM

Gopal said...

I think you could do better by adding few more multithreading and concurrency questions
from java.util.concurrent package e.g.

1) Difference between Callable and Runnable interface in Java?


2) What is FutureTask in Java? What is benefit of using it?
3) Difference between Thread.isInterrupted() and Thread.interrupt() method?
4) How ConcurrentHashMap achieves scalability?
5) What is Semaphore in Java?
6) Difference between ReentrantLock and synchronized keyword in Java?
7) What is ReadWriteLock in Java?
8) What is busy spinning?
9) Difference between notify() and notifyAll() in Java? When do you use notifyAll() over
notify()?
10) Difference between wait, sleep and yield in Java?
11) Difference between Runnable vs Thread in Java?
12) Why wait and notify methods are called from synchronized block or method in Java?
13) What is doubled checked locking of Singleton?
14) Difference between LiveLock and Starvation in Java?
15) What is daemon thread in Java? What is use of daemon threads?
16) Why wait, notify and notifyAll are in Object class instead of Thread?
17) Why wait method is called from loop in Java
18) Difference between wait method and Condition object in Java?
19) Write code for getInstance() method of thread-safe Singleton in Java?
20) What is Java Memory Model?
21) Can we make static method synchronized in Java?
22) What is lock stripping?
23) How many thread is created by Timer class?
24) What is ThreadLocal in Java?
25) What is ThreadLocal memory leak in Java? How to fix that?
26) What is race condition in Java? Have you ever faced race conditions?
27) What is thread-safety? What are few ways to achieve thread-safety in multithreading
code?
28) Difference between synchronized method and block in Java? Which one is better?
29) Difference between volatile and transient variable in Java?
30) How to check if a Thread holds a Lock in Java?

December 25, 2013 at 7:46 PM

cbp said...

Thanks for the list of questions and all the great comments. I wanted to point out an error
in #11 though.

When you call the start() method in the Thread class, it does not directly call the run()
method. It calls a native code method start0(). This native code will only schedule the
thread to be executed with the ThreadScheduler. The JVM will then grab the item from
the ThreadScheduler and execute the run() function. It is very similar to a Strategy
Pattern from GoF where the JVM knows how to execute a strategy and a Thread class
defines what the strategy is that is to be executed.

March 27, 2014 at 5:44 AM

Nihar Ranjan Khatua said...

Hi Guys,
This is Nihar.I have one question from threading concept i.e in an application 0-10 thread
is good or 10-100 thread..which one & why????

July 15, 2014 at 11:42 PM

Anonymous said...

This was asked in my recent interview .


Object ob1 has two methods A and B.
You have two Threads (Thread 1 and Thread 2)

Question is I should be access Method A of Ob1 from Thread 1 and at the same time
Thread 2 should be able to access Method B of Ob1.

However if Thread 1 is using Method A , then Thread 2 should not be able to use Method
A of Ob1.
How is this possible ?? One hint given was Monitors :-)

August 9, 2014 at 4:53 AM

Post a Comment

Read more: http://javarevisited.blogspot.com/2011/07/java-multi-threading-


interview.html#ixzz3XrjH3p3u

How to create Thread Pools using Java 1.5


Executor Framework - Example Tutorial
Read more: http://javarevisited.blogspot.com/2013/07/how-to-create-thread-pools-in-java-
executors-framework-example-tutorial.html#ixzz3XrjV3LEJ
Java 1.5 introduced Thread pool in Java in form of Executor framework, which allows Java programmer to decouple
submission of task to execution of task. If you are doing server side programming in Java than Thread pool is an
important concept to maintain scalability, robustness and stability of system. For those, who are not familiar with
thread pool in Java or concept of thread pool here is one liner, Thread pool in Java is pool of worker threads, which is
ready to perform any task given to them, mostly in form of implementation of Runnable or Callable interface. Since
Java supports multithreading in programming language itself, it allows multiple thread to run concurrently and perform
parallel processing of task. In this article we will learn following things about thread pool in Java :

1. What is Thread pool in Java?


2. Why do we need Thread pool in Java ?

3. What is Executor framework in Java 5?

4. How to create fixed size thread pool using Executor framework in Java?
5. Benefits of using Thread Pool in Java?
What is Thread Pool in Java and why we need it

As I said Thread pool is pool of already created worker thread ready to do the job. Thread pool is one of essential
facility any multi-threaded server side Java application requires. One example of using thread pool is creating a web
server, which process client request. If you are familiar with socket programming than you know that
ServerSocket.accept() is blocking method and blocks until a socket connection made. If only one thread is used
to process client request, than it subsequently limit how many client can access server concurrently. In order to
support large number of clients, you may decide to use one thread per request paradigm, in which each request is
processed by separate Thread, but this require Thread to be created, when request arrived. Since creation of Thread
is time consuming process, it delays request processing. It also limits number of clients based upon how many thread
per JVM is allowed, which is obviously a limited number. Thread pool solves this problem for you, It creates Thread
and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in
form of worker thread. Since Thread are usually created and pooled when application starts, your server can
immediately start request processing, which can further improve server’s response time. Apart from this, there are
several other benefits of using Thread pool in Java applications, which we will see in subsequent section. In short, we
need thread pools to better mange threads and decoupling task submission from execution. Thread pool and
Executor framework introduced in Java 5 is an excellent thread pool provided by library.

Java Thread Pool - Executor Framework in Java 5


Java 5 introduced several useful features like Enum, Generics, Variable arguments and several concurrency
collections and utilities like ConcurrentHashMap and BlockingQueue etc, It also introduced a full feature built-in
Thread Pool framework commonly known as Executor framework. Core of this thread pool framework is Executor
interface which defines abstraction of task execution with method execute(Runnable task) and
ExecutorService which extends Executor to add various life-cycle and thread pool management facilities like
shutting down thread pool. Executor framework also provides an static utility class called Executors ( similar to
Collections) which provides several static factory method to create various type of Thread Pool implementation in
Java e.g. fixed size thread pool, cached thread pool and scheduled thread pool. Runnable and Callable interface
are used to represent task executed by worker thread managed in these Thread pools. Interesting point about
Executor framework is that, it is based on Producer consumer design pattern, where application thread produces task
and worker thread consumers or execute those task, So it also suffers with limitation of Producer consumer task like
if production speed is substantially higher than consumption than you may run OutOfMemory because of queued
task, of course only if your queue is unbounded.
How to create fixed size thread pool using Executor framework in Java?
Creating fixed size thread pool using Java 5 Executor framework is pretty easy because of static factory methods
provided by Executors class. All you need to do is define your task which you want to execute concurrently and
than submit that task to ExecutorService. from them Thread pool will take care of how to execute that task, it can
be executed by any free worker thread and if you are interested in result you can query Future object returned by
submit() method. Executor framework also provides different kind of Thread Pool e.g. SingleThreadExecutor
which creates just one worker thread or CachedThreadPool which creates worker threads as and when necessary.
You can also check Java documentation of Executor Framework for complete details of services provided by this
API. Java concurrency in Practice also has couple of chapters dedicated to effective use of Java 5 Executor
framework, which is worth reading for any senior Java developer.

Example of Thread Pool in Java


Here is an example of Thread pool in Java, which uses Executor framework of Java 5 to create a fixed thread pool
with number of worker thread as 10. It will then create task and submit that to Thread pool for execution:

public class ThreadPoolExample {

public static void main(String args[]) {

ExecutorService service = Executors.newFixedThreadPool(10);

for (int i =0; i<100; i++){

service.submit(new Task(i));

final class Task implements Runnable{

private int taskId;

public Task(int id){

this.taskId = id;

}
@Override

public void run() {

System.out.println("Task ID : " + this.taskId +" performed by "


+ Thread.currentThread().getName());

Output:

Task ID : 0 performed by pool-1-thread-1

Task ID : 3 performed by pool-1-thread-4

Task ID : 2 performed by pool-1-thread-3

Task ID : 1 performed by pool-1-thread-2

Task ID : 5 performed by pool-1-thread-6

Task ID : 4 performed by pool-1-thread-5

If you look at output of this Java example you will find different threads from thread pool are executing tasks.

Benefits of Thread Pool in Java


Thread Pool offers several benefit to Java application, biggest of them is separating submission of task to execution
of task ,which result if more loose coupled and flexible design than tightly coupled create and execute pattern. Here
are some more benefits of using Thread pool in Java:

1) Use of Thread Pool reduces response time by avoiding thread creation during request or task processing.

2) Use of Thread Pool allows you to change your execution policy as you need. you can go from single thread to
multiple thread by just replacing ExecutorService implementation.

3) Thread Pool in Java application increases stability of system by creating a configured number of threads decided
based on system load and available resource.

4) Thread Pool frees application developer from thread management stuff and allows to focus on business logic.
That's all on Thread pool in Java 5. we have seen what is thread pool in Java, what is executor framework in java 5,
how to create thread pool in Java and some benefits of using thread pool in Java application. no doubt knowledge of
thread pool is essential for a server side core Java developer and I suggest reading Java Threads and Concurrency
Practice in Java to learn more about concurrency and thread pool.

Recommended Books in this article

Java Concurrency in Practice by Brian Goeatz, Doug Leaa, Joshua Bloch and team

Java Threads By Scott Oaks and Henry Wong

Effective Java by Joshua Bloach

You might like:

 How to use Fork Join in Java 1.7 - Tutorial with Example


 Counting Semaphore Example in Java 5 – Concurrency Tutorial

 How to find all Pairs in Array of Integers whose Sum is equal to a given Number

 How to use ConcurrentHashMap in Java - Example Tutorial and Working

Recommended by
Posted by Javin Paul at 6:23 AM

Email This BlogThis! Share to Twitter Share to Facebook

Labels: core java , core java interview question , Java multithreading Tutorials

Location: United States

5 comments :
vineet said...

Don't forget to call service.shutdown() on ExecutorService. Also why @Override on the


run() gives a compile error.

July 31, 2013 at 8:35 PM

Manoj Sharma said...


Thanks Javin, very nice article, this is really what I was looking from many days about
executor framework. Good job done. Best of luck

August 22, 2013 at 5:38 AM

Anonymous said...

Thank you, this is a very good reading!

April 11, 2014 at 12:07 AM

Anonymous said...

what will happen if one of the thread in thread pool throws exception.

May 13, 2014 at 9:26 PM

Anonymous said...

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Task implements Runnable {


private int id;

public Task(int id) {


this.id = id;
}

public void run() {


try {
//Thread.sleep(10000);
System.out.println(Thread.currentThread().getName() + "----" + id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

public class ThreadPool {

public static void main(String[] args) {


ExecutorService tPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 20; i++) {
tPool.submit(new Task(i));
}

tPool.shutdown();
try {
tPool.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}

}
}

July 30, 2014 at 12:23 PM

Post a Comment

Read more: http://javarevisited.blogspot.com/2013/07/how-to-create-thread-pools-in-java-executors-


framework-example-tutorial.html#ixzz3Xrjg1Moo
Exception handling
1.What I s Exception ?

Exception is abnormal conduction that can be handled .an Other Word An unwanted, unexpected
event that disturbs normal flow of the program is Exception.

2. What is Error?

That Abnormal conduction that can’t be handled that is called error .ex System failler.

3. What is the purpose of Exception handling ?

The main purpose of Exception of handling is for graceful termination of the program.

4. What is meaning of Exception handling ?

Exception Handling dosen’t mean repairing the exception we have to define alternative way to
continue the rest of code normally.

5. What is the purpose of the try block?

We should maintain the risky code inside try blog.

6. What is the purpose of the catch block ?

We have maintain all the Exception handling code in side the catch block.

7. What is try ?

Some time interviewer ask this type of question and try to confuse you but don’t confuse answer
is so simple try is key word in java. If interviewer ask what is try block than ans .

8. What is catch ?

Same case as a try catch is also key word in java.

9. Is try block with multiple catch Block possible?

Yes its possible You can Write a try block with multiple catch block for separate catch block for
every exception.

Ex. try{risky code;}

Catch(IOException e){}

Catch(ArithmaticException e){} etc.


10. If try multiple catch block present is order of catch block is important in which order
we have to take?

If try multiple catch block present is order of catch block is important it should from child to
parent not parent to child.

11. what are the various method in Exception class?

There are various method in Exception class

 printstackTrace() :- This Method print exception information in the following format.


Name of the Exception :Description StackTrase
 toString() This method print information in the following format. Name of the Exception
:Description
 getMessage() This method print only description of the exception

more……..

12. If an exception rised catch block what will happened ?

If an Exception raised in catch block and it is not part of any try block then it is always abnormal
termination.

13. it is possible try catch block inside the catch block?

Yes it is possible to take try,catch block inside the catch block.

14. what is the purpose of finally block ?

The main purpose of finally block is to maintain the cleanup code.This block will execute
always.

15. It is possible try block without catch block?

Yes It is possible try block without catch block using finally block it.

Ex. Try()finally{}

16.In which case finally block will not executed ?

There is one solution where the finally block wont be executed if we are using system.exit(0)
explicity then Jvm itself will be shoutdown and there is no chance of executing the finally block.

17. If return statement present in try block is finally block will be executed ?
Yes if return statement present in inside try block then also finally block will executed finally
block will dominate return statement also.

18. what is difference between final ,finally,finailize() ?

Final – final is modifier applicable on variable and methods and class.Final variable means
constant and reassign not be possible .

Finally – finally is block that assocated with try catch block to maintain the cleanup code.

Finalize() – Finalize is method of object class garbage collector always called this method just
before destroying any object to perform clean up activity.

19.Is it possible to write any code with in try and catch and finally block ?

No it is not possible to write any statement between try catch finally block .If we will try to write
ant statement between them we will get compiler error.

20. It is Possible two finally block for the some try ?

No it is not possible two finally block in same try. If we try to take then we will get compile time
error.

21. Is Syntax try-finally-catch is possible ?

No This syntax not valid.it should be like try-catch-finally than only code will compile.

22. What is porous of throw key word ?

Some time we create a Exception emplicitly and we can handover that exception object to the
JVM explicitly by throw keyword.

In other word throw key use the raise the exception.

Class Test {

Public static void main(String arhg[])

Throw new ArithmaticException(“/by zero”);

} }

23 It is possible throw an Error ?


Yes it is possible to throw an error any Throwbale type include Error/

24. Is it Possible throw an object ?

No we can use throw keyword only throwble object otherwise we will get compile time error

Saying Unreachible Statement.

25. What is the purpose of throws key word.

Throws keyword use to propagate the exception.

26.what is difference between throws and thrown?

This Type of question create the confusion in your mind don’t confuse there is no terminology
of thrown in java.

27 Explain the exception handling keyword?

Exception Handling Key word

 try
 catch
 finally
 throw
 throws

28.Which class of root class Java Exception Haierarchy?

Throwable class the top class of Exception hierarchy.

29. What is the difference between Exception and Error ?

Exception : These are our program and are recoverable

Error:-these are not caused by our program mostly caused by lake of system resources.These are
non recoverable.

30. What is difference between checked and unchecked Exception ?

That Exception Checked by compile Time is called checked exception.Ex.IOExcetopin .

The Exception which not checked by Compile time that checked by runtime is called unchecked
exception Ex.AruthMAticException /0;
31 What is difference partially checked and fully checked Exception?

A checked exception is said to be fully checked if and only if all the child calss also checked
otherwise it is calles partially checked exception.

IOexception:-fully checked exception

Exception : are partially checked .

32 What are the customized exception?

Sometime based won your programming required we have to create our own exception such type
exception called customize exception.

33.Con You give the name of most common exception occurred in your previous project?

NullPointerException,ArrayIndexOutOfBondException,StackOvweFlowException,CalssCastEx
ception,NoCalassDefFounError,etc.

34.How to Customize Your own Exception.?

- See more at: http://javaaster.com/2013/03/31/35-basic-exception-interview-question-and-


answer/#sthash.WyBhTOj4.dpuf
class TestError extends Error { TestError(String m) { super(m); } } class TestEr { public static
void main(String ar[]) { int a=0,b=1; if(b>a) { TestError e=new TestError("MyError"); throw e; }

State some situations where exceptions may arise in java?

What is Exception handling in java?

What is an eror in Java?

What are advantages of Exception handling in java?

In how many ways we can do exception handling in java?

Java revisited:
10 Java Exception and Error Interview
Questions Answers
Read more: http://javarevisited.blogspot.com/2013/06/10-java-exception-and-error-interview-
questions-answers-programming.html#ixzz3YmejLYXN

You will always see some interview questions from Exception and Error handling in core Java Interviews. Exception
handling is an important aspect of Java application development and its key to writing robust, stable Java programs,
which makes it natural favorites on interviews. Questions from Error and Exception in Java mostly based on concept
of Exception and Error in Java, How to handle Exception , best practices to follow during Exception handling etc.
Though multithreading, garbage collection, JVM concepts and questions from object oriented design rules these
interviews, you should always expect and prepare some questions on effective error handling. Some Interviewer also
test debugging skill of programmers, as resolving Exceptions quickly is another trait of solid Java programming
knowledge. If programmer is familiar with infamous and dodgy ClassNotFoundException or OutOfMemoryError, there
is a good chance that he has some good practical experience under his belt. In this article we will see some Java
Error and Exception interview questions asked to fresher, experienced and senior Java developers in Java J2EE
interviews.

Java Exception and Error Interview Questions

Here is my list of frequently asked questions from Java Error and Exception topics in various programming
interviews to Java and J2EE developers. I have also shared my answers for these questions for quick revision, and
provided source for more in depth understanding. I have tried to include questions of various difficulty level, including
simplest of simple for freshers and some tricky questions for senior Java developers. If you think, there is a good
question, which is not included in this list, please feel free to share it via comment. You can also share error handling
questions asked to you on interviews or any question, for which you don’t know the answer.

1) What is Exception in Java?

This is always been first interview question on Exception and mostly asked on fresher level interviews. I haven't seen
anybody asking about what is Exception in senior and experienced level interviews, but this is quite popular at entry
level. In simple word Exception is Java’s way to convey both system and programming errors. In Java Exception
feature is implemented by using class like Throwable, Exception, RuntimeException and keywords like
throw, throws, try, catch and finally. All Exception are derived form Throwable class. Throwable further
divides errors in too category one is java.lang.Exception and other is java.lang.Error.
java.lang.Error deals with system errors like java.lang.StackOverFlowError or
Java.lang.OutOfMemoryError while Exception is mostly used to deal with programming mistakes, non availability of
requested resource etc.
2) What is difference between Checked and Unchecked Exception in Java ?

This is another popular Java Exception interview question appears in almost all level of Java interviews. Main
difference between Checked and Unchecked Exception lies in there handling. Checked Exception requires to be
handled at compile time using try, catch and finally keywords or else compiler will flag error. This is not a
requirement for Unchecked Exceptions. Also all exceptions derived from java.lang.Exception classes are
checked exception, exception those which extends RuntimeException, these are known as unchecked exception
in Java. You can also check next article for more differences between Checked and Unchecked Exception.

3) What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java?

This is Java Exception interview question was not very popular, but appears in various fresher level interviews, to see
whether candidate is familiar with concept of checked and unchecked exception or not. By the way answer of this
interview question is both of them are example of unchecked exception and derived form RuntimeException. This
question also opens door for difference of array in Java and C programming language, as arrays in C are unbounded
and never throw ArrayIndexOutOfBoundException.

4) What best practices you follow while doing Exception handling in Java ?

This Exception interview question in Java is very popular while hiring senior java developer of Technical Lead. Since
exception handling is crucial part of project design and good knowledge of this is desirable. There are lot of best
practices, which can help to make your code robust and flexible at same time, here are few of them:

1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since NPE is most
infamous of all Java exceptions, there are lot of techniques and coding best practices to minimize
NullPointerException. You can check that link for some specific examples.

2) Non empty catch blocks. Empty catch blocks are considered as one of the bad practices in Exception handling
because they just ate Exception without any clue, at bare minimum print stack trace but you should do alternative
operation which make sense or defined by requirements.

3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it improves
readability of

code by removing boiler plate exception handling code

4) Never let your database Exception flowing till client error. since most of application deal with database and
SQLException is a checked Exception in Java you should consider handling any database related errors in DAO
layer of your application and only returning alternative value or something meaningful RuntimeException which
client can understand and take action.
5) calling close() methods for connections, statements, and streams on finally block in Java.

I have already shared lot of these in my post Top 10 Java exception handling best practices, you can also refer that
for more knowledge on this topic.

5) Why do you think Checked Exception exists in Java, since we can also convey error using
RuntimeException ?

This is a controversial question and you need to be careful while answering this interview question. Though they will
definitely like to hear your opinion, what they are mostly interested in convincing reason. One of the reason I see is
that its a design decision, which is influenced by experience in programming language prior to Java e.g. C++. Most of
checked exceptions are in java.io package, which make sense because if you request any system resource and its
not available, than a robust program must be able to handle that situation gracefully. By declaring IOException as
checked Exception, Java ensures that your provide that gracefully exception handling. Another possible reason could
be to ensuring that system resources like file descriptors, which are limited in numbers, should be released as soon
as you are done with that using catch or finally block. Effective Java book from Joshua Bloch has couple of items in
this topic, which is again worth reading.

6) What is difference between throw and throws keyword in Java?

One more Java Exception interview questions from beginners kitty. throw and throws keyword may look quite
similar, especially if you are new to Java programming and haven't seen much of it. Though they are similar in terms
that both are used in Exception handling, they are different on how and where they are used in code. throws
keyword is used in method signature to declare which checked exception method can throw, you can also declare
unchecked exception, but that is not mandatory by compiler. This signifies lot of things like method is not going to
handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time
exception handling etc. On the other hand throw keyword is actually used to throw any Exception. Syntactically you
can throw any Throwable (i.e. Throwable or any class derived from Throwable) , throw keyword transfers
control of execution to caller so it can be used in place of return keyword. Most common example of using throw in
place of return is throwing UnSupportedOperationException from an empty method as shown below :

private static void show() {

throw new UnsupportedOperationException("Not yet implemented");

See this article for more differences between these two keywords in Java.

7) What is Exception chaining in Java?


Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response
of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an
unchecked or RuntimeException. By the way if you are throwing new exception due to another exception then
always include original exception so that handler code can access root cause by using methods like getCause()
and initCause().

8) Have you written your own custom Exception in Java? How do you do that?

Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main purpose
of asking this Java Exception interview question is to find out how you use this feature. This can be used for
sophisticated and precise exception handling with tweak involved in whether you would choose a checked or
unchecked exception. By creating a specific exception for specific case, you also gives lot of options to caller to deal
with them elegantly. I always prefer to have a precise exception than a general exception. Though creating lots of
specific exceptions quickly increase number of classes in your project, maintaining a practical balance between
specific and general exceptions are key to success.

9) What changes has been introduced in JDK7 related to Exception handling in Java ?

A relatively new and recent Exception interview question in Java. JDK7 has introduced two major feature which is
related to Error and Exception handling, one is ability to handle multiple exception in one catch block, popularly
known as multi cache block and other is ARM blocks in Java 7 for automatic resource management, also known as
try with resource. Both of these feature can certainly help to reduce boiler plate code required for handling checked
exceptions in Java and significantly improves readability of code. Knowledge of this feature, not only helps to write
better error and exception code in Java, but also helps to do well during interviews. I also recommend reading Java 7
Recipes book to get more insight on useful features introduced in Java 7, including these two.

10) Have you faced OutOfMemoryError in Java? How did you solved that?

This Java Error interview questions is mostly asked on senior level Java interviews and here interviewer is interested
on your approach to tackle dangerous OutOfMemoryError. Admit it we always face this error no matter which kind
of project you are working so if you say no it doesn't go very well with interviewer. I suggest even if you are not
familiar or not faced it in reality but have 3 to 4 years of experience in Java, be prepare for it. At the same time, this is
also a chance to impress interviewer by showing your advanced technical knowledge related to finding memory
leaks, profiling and debugging. I have noticed that these skills almost always creates a positive impression. You can
also see my post on how to fix java.lang.OutOfMemoryError for more detail on this topic.

11) Does code form finally executes if method returns before finally block or JVM exits ?

This Java exception interview question can also be asked in code format, where given a code with System.exit()
in try block and something in finally block. It’s worth knowing that, finally block in Java executes even when return
keyword is used in try block. Only time they don’t execute is when you call JVM to exit by executing
System.exit(0)from try block in Java.
12) What is difference in final, finalize and finally keyword in Java?

Another classic interview question in core Java, this was asked to one of my friend on his telephonic interview for
core Java developer with Morgan Stanley. final and finally are keyword, while finalize is method. final
keyword is very useful for creating ad Immutable class in Java By making a class final, we prevent it from being
extended, similarly by making a method final, we prevent it from being overridden,. On the other hand, finalize()
method is called by garbage collector, before that object is collected, but this is not guaranteed by Java specification.
finally keyword is the only one which is related to error and exception handling and you should always have finally
block in production code for closing connection and resources. See here for more detailed answer of this question.

13) What is wrong with following code :

public static void start() throws IOException, RuntimeException{


throw new RuntimeException("Not able to Start");

public static void main(String args[]) {

try {

start();

} catch (Exception ex) {

ex.printStackTrace();

} catch (RuntimeException re) {

re.printStackTrace();

This code will throw compiler error on line where RuntimeException variable “re” is written on catch block.
since Exception is super class of RuntimeException, all RuntimeException thrown by start() method will be
captured by first catch block and code will never reach second catch block and that's the reason compiler will flag
error as “exception java.lang.RuntimeException has already been caught".
14) What is wrong with following code in Java:

public class SuperClass {

public void start() throws IOException{

throw new IOException("Not able to open file");

public class SubClass extends SuperClass{

public void start() throws Exception{

throw new Exception("Not able to start");

In this code compiler will complain on sub class where start() method gets overridden. As per rules of method
overriding in Java, an overridden method can not throw Checked Exception which is higher in hierarchy than original
method. Since here start() is throwing IOException in super class, start() in sub class can only throw either
IOException or any sub class of IOException but not super class of IOException e.g. Exception.

15) What is wrong with following Java Exception code:

public static void start(){

System.out.println("Java Exception interivew question Answers for Programmers");

public static void main(String args[]) {

try{

start();
}catch(IOException ioe){

ioe.printStackTrace();

In this Java Exception example code, compiler will complain on line where we are handling IOException, since
IOException is a checked Exception and start() method doesn't throw IOException, so compiler will flag error
as "exception java.io.IOException is never thrown in body of corresponding try
statement", but if you change IOException to Exception compiler error will disappear because Exception can be
used to catch all RuntimeException which doesn't require declaration in throws clause. I like this little tricky Java
Exception interview question because its not easy to figure out result by chaining IOException to Exception. You
can also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based on Java Errors and
Exceptions.

These are some of Java Error and Exception interview questions, I have mostly seen in both fresher and experienced
level of Java interviews. There are a lot more questions on Exception which I haven't included and if you think you
have a good question missed out than let me know and I will make effort to include it on this list of java exceptions
question and answers. One last question of Java Exception I am leaving for you guys is "Why Java Exception
considered to be better alternative of returning error codes" , let me know what is your thought
on this list of Java Exception interview questions and answers.

Recommended Books in this article

Effective Java By Joshua Bloch

Java 7Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime and John O'Conner

Java Puzzlers by Joshua a Bloch and Neil Gafter

You might like:

 Inter Thread Communication in Java using Wait Notify Example


 Top 10 Java Serialization Interview Questions and Answers

 How clone method works in Java

 Checked vs Unchecked Exception in Java Example


Read more: http://javarevisited.blogspot.com/2013/06/10-java-exception-and-error-interview-
questions-answers-programming.html#ixzz3Ymew7BXN

10 best practices with Exceptions


The author suggests:

buy this book

This article enumerates ten best practices to adopt when you are programming in Java and you
are using Exceptions.

An exception is an event that breaks the normal flow of the program. Any event may be an
exception, but in Java we normally use exceptions when errors happen. For this reason we
normally refer to exceptions as to the error handling system of Java.

This article will assume some basic knowledge about the exceptions and will attempt to provide
guidelines on how to best use them. If you find it hard to read this article refer to the tutorial
about exceptions from Sun, which gives a good basics on this topic.
Contents
[hide]

 1 Relevancy
 2 Encapsulation

 3 Reason

 4 Exception names

 5 Balance what you catch

 6 Scoping

 7 Use Finally

 8 Throw only Exceptions

 9 Throw early catch late

 10 Add validation

 11 Comments from the users

Relevancy

A method can only throw the exceptions that are relevant to its interface.

For example see the constructor:

java.io.FileInputStream.FileInputStream(String name) throws


FileNotFoundException

Which opens a file on the disk for reading bytes. It makes sense that this constructor throws a
FileNotFoundException. But it would make no sense at all if it would throw an
IndexOutOfBoundsException. This exception would not be meaningful in the
FileInputStream context.

So keep the exceptions you throw relevant to the interface.

Encapsulation

To follow the principle of relevancy it may be useful the trick of encapsulating exceptions one
into another.

For example if your method is throwing an exception received from another method (which is a
very common scenario) it should encapsulate it in a locally generated Exception class.
Like it's shown in the example:

try {
return new FileOutputStream(fileName);
} catch (FileNotFoundException e) {
throw new ActionException(e);
}

The method receives an Exception generated by the FileOutputStream constructor, and throws
it to the next method in the stack trace encapsulating it in a ActionException, so it throws only
exceptions that are relevant to the interface.

The method that catches this exception can at any time get the information about the
FileNotFoundException, encapsulated in the main exception, by using the getCause()
method.

If you print the stack trace you will see a list of caused by: strings, containing all relevant
information about all the nested exceptions.

Reason

The exceptions must always say what caused them. There are two viable approaches:

 To generate a separate exception for each event.


 To create a generic exception and describe what caused it

The first approach allows you to write different code for handling the different events, but it
requires you to write lot of Exception classes and in some case it could be just too much.

The second approach is more concise, but it makes it difficult to handle the different situations.

As it happens very often in programming the best solution is in the middle, where you balance
generating separate exceptions and using one exception for other cases.

The rule of the thumb in this case could be to generate a separate Exception class for the
exceptions you want to handle specifically with separate code, while use a single generic
Exception class for exceptions you want to treat in a default way, for example you just want to
bubble them up the stack trace to show an error message.

Exception names

The names of the exceptions should always be meaningful and must express what happened that
caused them. For example java.io.FileNotFoundException has a good name and tells you
that a file was not found. The class java.lang.Exception provides a generic exception class for
all the situations that are not managed by the JDK API. My advice is to avoid using the
java.lang.Exception as it is too generic and gives too little information about what went
wrong.

My approach is that whenever I feel like throwing java.lang.Exception I instead create a new
exception class that subclasses java.lang.Exception. I use this new Exception class to manage
the generic errors generated by my class.

For example, if I am writing the Draw class and see that in one of it's methods I need to throw an
exception, I can create the DrawException class, extending java.lang.Exception.

DrawException works exactly in the same way as Exception, but when I see it in the stacktrace
if the exception occurs, I understand immediately who generated it and when and why. When my
program grows a little and I start using the encapsulation principle mentioned before in this
article I will end up with a stacktrace with all caused by: followed by names of classes I wrote.
This simplifies debugging a lot.

We used this principle in the example mentioned above (repeated here):

try {
return new FileOutputStream(fileName);
} catch (FileNotFoundException e) {
throw new ActionException(e);
}

The ActionException class would be as simple as follows:

package org.wikijava.network.batBot.delegates.interfaces;

public class ActionException extends Exception {

public ActionException() {
// TODO Auto-generated constructor stub
}

public ActionException(String message) {


super(message);
// TODO Auto-generated constructor stub
}

public ActionException(Throwable cause) {


super(cause);
// TODO Auto-generated constructor stub
}

public ActionException(String message, Throwable cause) {


super(message, cause);
// TODO Auto-generated constructor stub
}

}
This class was completely automatically generated by Eclipse. Note that It contains only the four
constructors. All the other methods are inherited from java.lang.Exception

Balance what you catch

Similarly to the reason principle not only we can decide what to throw, we have control also on
what to catch. We can use two approaches for our catch blocks:

 a single catch block for all. For example:

} catch (Throwable e) {
throw new CommandExecutorException(e);
}
 many catch blocks one for each Exception. For example:

} catch (ClassCastException e1) {


...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}

The first approach is very compact but basically groups every exception in the same case, it's
useful only in the situation where all the exceptions are managed equally and do the same thing,
for example they bubble up to the view and become a message to the user. This approach is
generally discouraged as it gives no control on the exceptions being catched, leading sometimes
to tough bugs, which are also hard to find.

The second approach requires more lines of code but you can execute different operations
depending on the exception occurred. This approach is more flexible but in some cases leads
your methods to be very long due to exception handling. This is normally the most accepted way
of catching exceptions.

If you use properly the encapsulation, relevancy and the Scoping principles you should already
mitigate a lot this problem, and you should not have too long series of catch blocks.

Scoping

How long should a try block be? Should you write a try-block for a whole method or a try
block for each single operation throwing something?

If you write too few try-blocks you risk your exception not to be meaningful and it won't help
you to understand what's the problem when debugging. On the other hand if you write too many
try-blocks. you end up with your code cluttered with exception management code, variables
with strange scope and other ugly situations.
Once again the best solution is in the middle. Try to use try blocks wisely, grouping operations
cleverly in order to balance the simplicity of your code, with the granularity of your exception
management. I recommend minding the following consideration:

Use the try-blocks to enhance the scoping of your variables.

If you have a variable used only in a small part of your method, then you can use the try-block
to delimit it's scope.

Use try-blocks to delimit your operations

You can split your code in several try catch blocks where each try is doing something specific.
This delimitations make your code more readable.

Granularity of your exception handling

If you want your program to handle the exception in a very granular way, by catching every single
exception and doing something appropriate with it. Then you probably want also to know
exactly which operation generated it. You lose this information if you have more operations in
one try-block.

Size of your code

It's normally better to write each block of code so that it can be seen all together on the screen.
So if you write a method which is too long (you shouldn't really though) you can use the try-
blocks to split the code to make it easier to read.

Number of exceptions thrown

This links to the Balance what you catch principle, where you want also to reduce the number of
catches after a try-block in order to make your code easier to read.

If you balance the dimension of your try-blocks keeping in mind these considerations you
should obtain a code elegantly written and easily readable.

Use Finally

Very often Programmers forgot about the finally block that you can attach to the try catch blocks.

The finally block is some code that it's executed anyway if the try block is successful or if an
exception was thrown. This is very important when you are dealing with system resources, such
files or database connections. If an exception was thrown (and normally you can't really be sure
when to expect it) then it can happen that you may miss to execute some clean up code and leave
resources allocated, or objects in an inconsistent state.

you can see it in action in the following example (from Split File :
FileWriter output= null;
try {
output = new FileWriter(file);
output.write(stringBuffer.toString());
System.out.println("file " + path + filename + " written");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Throwable e) {
e.printStackTrace();
}
}

The side effect is that very often you end up needing to nest try&catch blocks within the finally
blocks. There's a danger here because you could write:

try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}

but this would collide with the catch (IOException e) outside the finally and generate
dangerous, hard to debug situations.

Throw only Exceptions

In Java you can throw just anything, you are not bound to throw Exceptions. If you create your
own class and extend the java.lang.Throwable class to make your class throwable and able to
be handled in the same way as other exceptions or errors. But Throwable was thought
specifically for error and exception handling, it's better to stick to that and not use this
mechanism for other purposes. Forgetting this principle would drastically reduce the readability
of your code and lead you to potential debugging nightmares.

Throw early catch late

This is probably the most famous principle about Exception handling. It basically says that you
should throw an exception as soon as you can and catch it late, wait until you have all the
information to handle it properly.

This principle implicitly says that you will be more likely to throw it in the low level methods,
where you will be checking if single values are null or not appropriate. And you will be making
the exception climb the stack trace for quite several levels until you reach a sufficient level of
abstraction to be able to handle the problem. Ultimately you may reach the GUI to ask the user
what to do, or even to the main, and manage a neat exit of the program.
Add validation

At some points in your application you know what to expect, and you generally assume that your
inputs are correct. It's sometimes a good idea to to double check your inputs, to make sure that
they are what you expect and throwing and exception if they are not. This is useful because it
makes obvious by reading the code what you expect at specific points, so it increases the
readability, plus it create some fixed points that alert you if during the execution something went
wrong.

For example a validation I do quite often is similar to the following:

if ( null == variable || variable.isEmpty()){


throw new blahException("the variable cannot be null at this point");
}

It's not necessary to be maniac about this, and clutter your code with variable validations. A good
rule I follow is to add these validations whenever I'm solving a bug, in this way if the bug gets
introduced again, I can spot it quickly.

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the
top of the page

Nice tips

Thx for this article, very interesting !

Jmix from http://lexique-du-net.com/blog/

--193.54.225.89 12:04, 14 January 2009 (UTC)

Encapsulation VS "Throw early catch late"

Nice article!

In layered architecture such as web -> service -> repository(dao) these two principles i.e
Encapsulation and "Throw early catch late" some how seem to conflict. It makes sense to for
each layer to encapsulate exception and throw it further. For example service layer will catch
repository specific exceptions and encapsulate these with service exception and throw it to web
layer. However this defeats the principle of "CATCH LATE" and some times just becomes an
over head. Any thoughts/work arounds?
Thanks, Mohit Manrai

--193.130.13.233 12:06, 14 January 2009 (UTC)

Encapsulation VS "Throw early catch late"

Thank you Mohit.

Thanks for your comment. I think when you are doing encapsulation you are not really catching
the exception but just forwarding it to the next level, and leaving a trace of where the exception
has passed by. The real catch happens when you really do something with it and don't forward
the exception any more.

I don't think nesting all these exceptions is an overhead, consider the case where you are using a
DAO interface which is implementation independent and you can't sayif the DAO will access a
local DB, a remote DB or even a plain XML file.

From the point of view of the client of the DAO it doesn't make sense to be catching several
exceptions like UnableToConnectException, FileNotFoundException or SQLExceptions.
Catching all these would be the real overhead.

Your DAO may be able to deal with these exceptions and catch them straight there. Or it may be
not able to solve them and just pop them up encapsulated for example into a DAOException. The
DAOException would climb up the levels until it gets to a method able to deal with it (throw
early catch late). Thanks to encapsulation this method would easily get the list of Exceptions
nested and thus know where the exception has passed by and have great detail on what went
wrong. In complex situations this may result useful because he may get the similar exceptions
from different contexts and be able to find the best solution.

For example if a method catches a ShapeException thrown by some method called in its body, it
may be interesting to know what shape was causing the problem if it was a triangle or a square.
Plus it may be useful to know if it was in a box or in a notebook if the triangle was in a box or in
a notebook. it may be:

 ShapeException->BoxException->TriangleException or a
 ShapeException->NotebookException->TriangleException

using encapsulation in this way you can have all the information you need about the exception
directly inside the exception. This doesn't add too much complexity, and in the event your
program will grow in dimensions, you have a very scalable exception handling mechanism in
place. Hope this answers your question.

--DonGiulio 12:20, 14 January 2009 (UTC)


RE: Encapsulation VS "Throw early catch late"

Mohit Manrai : Encapsulating exceptions just because we want to encapsulat it, is not a good
practice, and leads to overhead you had mentioned. We want to encapsulate exceptions, because
we want to hide the details of inner implemenation from the outside:

- we do not want to make compile-time dependences to exceptions declared in


some inner libraries/layers we depend
- we want to leave us freedom of change the details of inner
implemantation, and used libraries/layers. Declaring exceptions from inner
libraries in interface methods would stick us to those libraries.

Encapsulate, if one of the above criteria is meet.

"catch late" does not mean literally 'catch' in this sentence. It is more like 'serve' - do some
concrete response to the unexpected situaltion reported by the exception. This does not mean
'catch, encapsulate and throw'.

By the way, who knows why the above example of "use finally" is an antipattern? Because, in
this wrongly coded example, any exception thrown by new FileWriter(fileName) would be
hidden by NullPointerException throw from line 'output.close()'. This is not the worst case,
because we used e.printStackTrace() before. At least we will have any log in the console. More
danger would be, when we would use encapsulation instead of e.printStackTrace() - than,
original exception would be lost.

Best Regards Marcin Sarniak Isolution Java Blog

--89.76.110.14 13:26, 14 January 2009 (UTC)

RE: Encapsulation VS "Throw early catch late"

Marcin: how would you solve that antipattern?

thanks & regards, --DonGiulio 13:51, 14 January 2009 (UTC)

Marcin Sarniak

First two thoughts:


If (output != null) {
output.close()
}

or

catch (Throwable th) in finally <-- in finally designed to clean resources, with none specific
business logic, it is acceptable, because safer: does not hide the primary exception.

--89.76.110.14 14:03, 14 January 2009 (UTC)

Good Thank you Marcin. Where would you put the if in your first thought? I updated the article
with your second solution.

thanks, --DonGiulio 14:14, 14 January 2009 (UTC)

Response

Hello, In my first proposed sollution, I was thinking of:

try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}

BR, Marcin Sarniak http://blog.isolution.pl

--89.76.110.14 16:11, 14 January 2009 (UTC)

Thanks

Thank you DonGiulio & Marcin for your response

Mohit Manrai

--193.130.13.233 16:50, 15 January 2009 (UTC)


GD2

I believe the best way is to explicitly throw a custom exception when ever the user needs to be
informed of a undesired event - like zero balance in case of a banking checkout system etc. For
all other cases, its best to catch the exception and log it and throw a new runtime exception
(preserving the stack trace) and catch it at a central handler. This would remove a lot of boiler
plate code in the whole project.

--GD2 09:53, 4 April 2011 (PDT)

tuna tore

very good article thanks

Potrebbero piacerti anche