30+ Core Java multithreading interview questions and answers
Java Multi-threading Interview Questions and Answers
Q. Why do interviewers like multi-threading interview questions?
A. Because it is not easy, but very essential to write scalable and high throughput systems.
If you are going for Java interviews to work on large scale systems, expect multi-threading interview questions. These are more beginner or fresher level questions and if you are already good with the basics, try more intermediate to advanced level coding questions and answers on Java multi-threading at Java multi-threading-1 | Java multi-threading-2
Q. What is the difference between processes and threads?
A. A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.
Q. Explain different ways of creating a thread?
A. Threads can be used by either
- Extending the Thread class.
- Implementing the Runnable interface.
- Using the Executor framework (this creates a thread pool)
class Counter extends Thread { //method where the thread execution will start public void run(){ //logic to execute in a thread } //let’s see how to start the threads public static void main(String[] args){ Thread t1 = new Counter(); Thread t2 = new Counter(); t1.start(); //start the first thread. This calls the run() method. t2.start(); //this starts the 2nd thread. This calls the run() method. } }
class Counter extends Base implements Runnable{ //method where the thread execution will start public void run(){ //logic to execute in a thread } //let us see how to start the threads public static void main(String[] args){ Thread t1 = new Thread(new Counter()); Thread t2 = new Thread(new Counter()); t1.start(); //start the first thread. This calls the run() method. t2.start(); //this starts the 2nd thread. This calls the run() method. } }
The thread pool is more efficient and learn why and how to create pool of threads using the executor framework.
Q. Which one would you prefer and why?
A. The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.
Q. Briefly explain high-level thread states?
A. The state chart diagram below describes the thread states.
- Runnable — A thread becomes runnable when you call the start( ), but does not necessarily start running immediately. It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
MyThread aThread = new MyThread(); aThread.start(); //becomes runnable
- Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
- Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
- Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
- Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
- Blocked on synchronization: will move to running when a lock is acquired.
- Dead: The thread is finished working.
Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These thread states are possible due to Java's following thread concepts:
- The objects can be shared and modified (i.e. if mutable) by any threads.
- The preemptive nature of the thread scheduler can swap threads on and off cores in a multi-core CPU machine at any time.
- This means the methods can be swapped out while they are running. Otherwise a method in an infinite loop will clog the CPU forever leaving the other methods on different threads to starve.
- To prevent thread safety issues, the methods and block of code that has vulnerable data can be locked.
- This enables the threads to be in locked or waiting to acquire a lock states.
- The threads also get into the waiting state for I/O resources like sockets, file handles, and database connections.
- The threads that are performing I/O read/write operations can not be swapped. Hence, they need to either complete to the finished state with success/failure or another thread must close the socket for it to get to the state of dead or finished. This is why proper service timeout values are necessary to prevent the thread to get blocked for ever in an I/O operation, causing performance issues.
- The threads can be put to sleep to give other threads in waiting state an opportunity to execute.
Q. What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )?
A. When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep ( ), it changes from running state to waiting/sleeping state.
The method wait(1000) causes the current thread to wait up to one second a signal from other threads. A thread could wait less than 1 second if it receives the notify( ) or notifyAll( ) method call. The call to sleep(1000) causes the current thread to sleep for t least 1 second.
Q. Why is locking of a method or block of code for thread safety is called "synchronized" and not "lock" or "locked"?
A. When a method or block of code is locked with the reserved "synchronized" key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means,
- When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object from the main heap memory to ensure that the thread that has the lock has the current info before start executing.
- After the synchronized block has completed and the thread is ready to relinquish the lock, all the changes that were made to the object that was locked is written or flushed back to the main heap memory so that the other threads that acquire the lock next has the current info.
This is why it is called "synchronized" and not "locked". This is also the reason why the immutable objects are inherently thread-safe and does not require any synchronization. Once created, the immutable objects cannot be modified.
Q. How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block?
A. In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method.
The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. For static methods, you acquire a class level lock.
More Interview Q&A on Java multithreading:
Beginner:
- Java multithreading questions and answers -- synchronization, daemon thread, inter thread communication
- Java coding question and answer on multi-threading
Intermediate to Advanced
- Java multi threading questions and answers -- coding
- Java multi threading questions and answers -- atomic operations
Articles on Java 5 concurrent package
- Article: Scenarios and solutions for better concurrency and thread safety part-2 CountDownLatch and CyclicBarrier
- Article: Scenarios and solutions for better concurrency and thread safety part-3 Semaphores and mutexes
Labels: Multi-threading
41 Comments:
Excellent Article.....
Indeed Threading is most confusing topic of Java and most asked topic also and confusion only increased with new concurrent package. thanks for your tips quite useful for beginners. I have also shared my experience as Top 10 multi-threading interview questions , do let me know how do you find it.
Just read the first couple lines, and love your article already! Good work!
how come the timestamp show "2015-09-19"?
That is a blogspot work around for a particular post to be the home page.
very well explained. I really liked the images you have created to visualize the threading concepts. Its very difficult otherwise. Thanks for sharing.
Good Article, Nice explanations
Diagrams and code snippets do help in grasping the concepts.
Excellent questions
Excellent work. Thanks
excellent article...another article i suggest is top 30 core java interview questions and answers
great article
Nice blog postings, thanks for your update on java questions.
Hi ArulKumaran,
A must blog for learning threading concepts, Looking forward to order your book. Just wnat to know that does your book contain spring and wicket interview question or not.. Iam new to These framework . I really like these framework , but have difficulty in visualizing things. I will wait for your answer
awesome!!!
its really good. Multi threading is very important and complex part in java. would like to read some more questions on the same..
if you click on the link below, there are more advanced questions and answers
Hi to all i am Rayudu...............I need Project Details
Not sure what you mean by project details.
As per state chart diagram, it shows that 'Blocked or synchronized' state will directly move to running state. But it is not quite matching with description.
I have fixed that Kavi. Thanks for pointing that out.
Thanks Arun!
Very well explained. Much appreciate the effort.
This was really interesting information. Thanks to share with us.
For shape up your career visit
Career
Careers
Hi Arul,
I have a question related to :
what is the difference between and Extending Thread and implementing Runnable interface and when to use.
Can u explain in simple way and in interview prospective I was confused.
Please Explain me.
In Java, a class can extend only one other class. Multiple inheritance is not allowed. If you use extends Thread, then that class can't extend any other classes. But if you use implements Runnable, then it can extend some other class if required. A Java class can implement multiple interfaces, but can extend only one other class.
Hi Arulkumaran, I want to learn Hard Core Java concept like Heap memory allocation, garbage collection etc. If your book "Core Java Career Essential" cover this topic as well. If no, can you suggest me some good books or site.
Deepak
The book does not cover the 2 topics you had mentioned. Google for it and you should get some good articles on it.
For example, try the following URLs to get started -->
http://javarevisited.blogspot.com.au/2011/04/garbage-collection-in-java.html
http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
http://www.javaworld.com/javaworld/jw-08-1996/jw-08-gc.html
http://www.vogella.com/articles/JavaPerformance/article.html
Explain different ways of creating a thread?
A. Threads can be used by either
Extending the Thread class.
Implementing the Runnable interface.
Implementing the callable interface
Hi Arulkumaran,
One conceptual doubt on Sleep method and Thread states.
Consider the situation:
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
Now as we all know that lock will not be released by the current running thread.
Now as per state diagram, if current thread has called sleep method, it will move to Sleeping state and then to runnable state after it is either interrupted or has slept for the specified duration. Now since the lock has not been released and the current thread has moved to runnable state rather than runnning state, will not it cause a deadlock or potential deadlock situation.
Thanks & Regards,
Sumit
Write the sample code, and see what happens.
Could not locate any information about the keyword: "volatile"
Is it explained elsewhere?
Hello Arun,
Excellent and easy to understand explanation.
Could you include usage of the synchronized keyword ....
For example a java class (implementing runnable) having 3 methods ....
Method ONE: public void m1()
Method TWO: public void static m2()
Method THREE: public void m3() ... with a synchronized block within.
How will this class behave .... in case of T1.m1(), T1.m2(), T2.m1(), T2.m3()
Where T1, T2 refer to threads invoking the methods.
thank you.
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.In interviews, normally questions start with some basic concept of the subject and later they continue based on further discussion.
Nice Article, please correct the following, notify or notifyall cant be used on sleep
The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1 second if it receives the notify( ) or notifyAll( ) method call.
good sample. interviewers seems just to think questions when they are on the table with you. thats why they usually think of the most common questions on core java, etc
One question. Can you please change the line" changes from running state to waiting/sleeping state.
The method wait(1000), causes the current thread to sleep up to one second."
There are two mistakes over there. For junior developers it might create wrong impression.
Arulkumaran , does your books available in book shops or it is available only in online shopping ?
Predominantly online stores.
Thanks for sharing i got lot of information it will be very helpful in my success.
Post a Comment
Subscribe to Post Comments [Atom]
<< Home