Google

Sep 19, 2013

30+ Core Java multithreading interview questions and answers

Java Multi-threading Interview Questions and Answers

Beginner Q&A More beginner Q&A Beginner locks Beginner thread communication Beginner thread sequencing Intermediate Q&A Volatile variable
Advanced Q&A Printing odd and even numbers Thread pools ExecutorService Atomic operations CountDownLatch and CyclicBarrier Semaphores and mutexes

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:
Intermediate to Advanced

Articles on Java 5 concurrent package


Labels:

41 Comments:

Anonymous Anonymous said...

Excellent Article.....

4:08 AM, January 24, 2012  
Anonymous Javin @ hostname to IP address in windows said...

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.

11:51 PM, February 22, 2012  
Anonymous Shadeven said...

Just read the first couple lines, and love your article already! Good work!

10:40 PM, March 10, 2012  
Anonymous Anonymous said...

how come the timestamp show "2015-09-19"?

2:11 PM, March 12, 2012  
Blogger Unknown said...

That is a blogspot work around for a particular post to be the home page.

2:20 PM, March 12, 2012  
Anonymous FromDev said...

very well explained. I really liked the images you have created to visualize the threading concepts. Its very difficult otherwise. Thanks for sharing.

4:17 AM, March 18, 2012  
Anonymous Software Testing Interview Questions said...

Good Article, Nice explanations

6:54 PM, March 20, 2012  
Blogger Unknown said...

Diagrams and code snippets do help in grasping the concepts.

5:45 PM, March 22, 2012  
Anonymous Anonymous said...

Excellent questions

10:50 AM, April 05, 2012  
Anonymous Anonymous said...

Excellent work. Thanks

6:37 PM, April 05, 2012  
Anonymous design pattern tutorial with real world examples said...

excellent article...another article i suggest is top 30 core java interview questions and answers

7:15 AM, April 14, 2012  
Anonymous top 30 core java interview questions and answers said...

great article

7:16 AM, April 14, 2012  
Anonymous Interview Tips said...

Nice blog postings, thanks for your update on java questions.

12:34 AM, April 28, 2012  
Anonymous Rohan Dekate said...

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

6:44 PM, June 08, 2012  
Anonymous Anonymous said...

awesome!!!

7:28 PM, June 24, 2012  
Blogger Pooja said...

its really good. Multi threading is very important and complex part in java. would like to read some more questions on the same..

5:35 PM, June 29, 2012  
Blogger Unknown said...

if you click on the link below, there are more advanced questions and answers

5:49 PM, June 29, 2012  
Anonymous Anonymous said...

Hi to all i am Rayudu...............I need Project Details

6:09 PM, July 18, 2012  
Blogger Unknown said...

Not sure what you mean by project details.

7:20 PM, July 18, 2012  
Blogger kavi said...

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.

2:31 AM, August 16, 2012  
Blogger Unknown said...

I have fixed that Kavi. Thanks for pointing that out.

10:28 AM, August 16, 2012  
Blogger kavi said...

Thanks Arun!

4:17 AM, August 21, 2012  
Blogger nk said...

Very well explained. Much appreciate the effort.

6:58 PM, September 05, 2012  
Blogger Unknown said...

This was really interesting information. Thanks to share with us.

For shape up your career visit
Career
Careers

12:40 AM, October 06, 2012  
Blogger suresh said...

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.

5:51 PM, October 08, 2012  
Blogger Unknown said...

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.

6:00 PM, October 08, 2012  
Anonymous Anonymous said...

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

1:43 PM, October 20, 2012  
Blogger Unknown said...

The book does not cover the 2 topics you had mentioned. Google for it and you should get some good articles on it.

5:53 PM, October 20, 2012  
Blogger Unknown said...

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

6:49 PM, October 20, 2012  
Anonymous Anonymous said...

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

2:10 AM, January 28, 2013  
Blogger Sumit said...

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

3:00 PM, March 13, 2013  
Blogger Unknown said...

Write the sample code, and see what happens.

10:38 PM, March 16, 2013  
Blogger Java son said...

Could not locate any information about the keyword: "volatile"

Is it explained elsewhere?

7:57 PM, April 05, 2013  
Blogger Java son said...

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.

2:29 PM, April 07, 2013  
Anonymous java certification said...

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.

3:30 PM, August 15, 2013  
Anonymous Anonymous said...

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.

5:09 PM, October 02, 2013  
Anonymous beginner said...

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

10:41 AM, February 07, 2014  
Blogger Unknown said...

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.

3:28 AM, March 06, 2014  
Blogger lonely ....but still standing said...

Arulkumaran , does your books available in book shops or it is available only in online shopping ?

4:42 PM, June 21, 2014  
Blogger Unknown said...

Predominantly online stores.

5:43 PM, June 21, 2014  
Blogger Unknown said...

Thanks for sharing i got lot of information it will be very helpful in my success.

8:30 PM, July 30, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home