Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Why wait notify and notifyAll called from synchronized block or method in Java
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
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.
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.
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
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.
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.
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 –
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?
Recommended by
Posted by Javin Paul at 6:08 AM
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
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.
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
@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
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.
Anonymous said...
java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()
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
Anonymous said...
Question: what are the benfits we will get when we extend a java.lang.Thread class
instead of implimenting Runnable interface?
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.
Thanks Arul. you like these thread interview questions. glad to here that.
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
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.
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
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?
@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.
Anonymous said...
Anonymous said...
Javin, really good questions. Just another query which core java book you recommned to
understand concepts.
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
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
Andrew 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!
Best wishes..
package com.learning.material;
/**
* @param args
*/
public static void main(String[] args) throws InterruptedException {
Gopal said...
I think you could do better by adding few more multithreading and concurrency questions
from java.util.concurrent package e.g.
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.
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????
Anonymous said...
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 :-)
Post a Comment
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.
service.submit(new Task(i));
this.taskId = id;
}
@Override
Output:
If you look at output of this Java example you will find different threads from thread pool are executing tasks.
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.
Java Concurrency in Practice by Brian Goeatz, Doug Leaa, Joshua Bloch and team
How to find all Pairs in Array of Integers whose Sum is equal to a given Number
Recommended by
Posted by Javin Paul at 6:23 AM
Labels: core java , core java interview question , Java multithreading Tutorials
5 comments :
vineet said...
Anonymous said...
Anonymous said...
what will happen if one of the thread in thread pool throws exception.
Anonymous said...
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
}
}
tPool.shutdown();
try {
tPool.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}
}
}
Post a Comment
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.
The main purpose of Exception of handling is for graceful termination of the program.
Exception Handling dosen’t mean repairing the exception we have to define alternative way to
continue the rest of code normally.
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 ?
Yes its possible You can Write a try block with multiple catch block for separate catch block for
every exception.
Catch(IOException e){}
If try multiple catch block present is order of catch block is important it should from child to
parent not parent to child.
more……..
If an Exception raised in catch block and it is not part of any try block then it is always abnormal
termination.
The main purpose of finally block is to maintain the cleanup code.This block will execute
always.
Yes It is possible try block without catch block using finally block it.
Ex. Try()finally{}
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.
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.
No it is not possible two finally block in same try. If we try to take then we will get compile time
error.
No This syntax not valid.it should be like try-catch-finally than only code will compile.
Some time we create a Exception emplicitly and we can handover that exception object to the
JVM explicitly by throw keyword.
Class Test {
} }
No we can use throw keyword only throwble object otherwise we will get compile time error
This Type of question create the confusion in your mind don’t confuse there is no terminology
of thrown in java.
try
catch
finally
throw
throws
Error:-these are not caused by our program mostly caused by lake of system resources.These are
non recoverable.
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.
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.
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.
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.
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.
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
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.
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 :
See this article for more differences between these two keywords in Java.
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.
try {
start();
ex.printStackTrace();
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:
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.
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.
Java 7Recipes: A Problem-Solution Approach By Josh Juneau, Carl Dea, Freddy Guime and John O'Conner
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
6 Scoping
7 Use Finally
10 Add validation
Relevancy
A method can only throw the exceptions that are relevant to its interface.
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.
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:
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.
try {
return new FileOutputStream(fileName);
} catch (FileNotFoundException e) {
throw new ActionException(e);
}
package org.wikijava.network.batBot.delegates.interfaces;
public ActionException() {
// 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
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:
} catch (Throwable e) {
throw new CommandExecutorException(e);
}
many catch blocks one for each Exception. For example:
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:
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.
You can split your code in several try catch blocks where each try is doing something specific.
This delimitations make your code more readable.
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.
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.
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.
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.
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.
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.
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
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
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.
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:
"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.
Marcin Sarniak
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.
Good Thank you Marcin. Where would you put the if in your first thought? I updated the article
with your second solution.
Response
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Thanks
Mohit Manrai
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.
tuna tore