27 Java Multithreading Interview Questions and Answers

Dear Readers, Welcome to Java Multithreading Interview questions with answers and explanation. These 27 solved Multithreading questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky Java Multithreading questions, you can easily attempt the objective type and multiple choice type questions on Multithreading.

Preemptive scheduling vs. time slicing.

In preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.

In time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks.
The scheduler then determines which task should execute next, based on priority and other factors.

Briefly explain daemon thread.

Daemon thread is a low priority thread which runs in the background performs garbage collection operation for the java runtime system.

What are the two types of multitasking?

Process-based and Thread-based.

Process and Thread

- A process can contain multiple threads.
- A process has its own memory address space whereas a thread doesn't.
- Threads share the heap belonging to their parent process.
- One process cannot corrupt another process
- A thread can write the memory used by another thread.

Name the ways to create the thread.

Implementing Runnable and Extending Thread

What is timeslicing?

Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.

Name the methods available in the Runnable Interface.

run()

Name the methods available in the Thread class.

isAlive(), join(), resume(), suspend(), stop(), start(), sleep(), destroy().

Write the signature of the constructor of a thread class.

Thread(Runnable threadobject,String threadName)

Name the methods used for Inter Thread communication.

wait(),notify() & notifyall()

Name the mechanism defined by java for the Resources to be used by only one Thread at a time.

Synchronisation

Data type for the parameter of the sleep() method is ____________

long

Provide the values for max-priority, min-priority and normal-priority level.

10,1,5

Name the method for setting the priority.

setPriority()

Name the default thread at the time of starting the program.

main thread.

How many threads at a time can access a monitor?

one

Name the four states associated in the thread.

new, runnable, blocked, dead

What is the priority for Garbage collector thread?

low-priority

What is a Thread?

We can describe "thread" in two ways in Java.

1. An instance of class java.lang.Thread.
2. A thread of execution.

An instance of Thread is an object like all other objects in Java, it also has variables and methods and it lives and dies on the heap.

- But a thread of execution is an individual light weight process that has its own call stack.
- Even if you don't create any new threads in your program, threads are there running in background.
- The main() method runs the main thread. So in main call stack the main() method would be the first.
- When a new thread is created then it will have its own stack separate from the main() call stack.

Can you tell some ways in which a thread can enter the waiting state?

A thread can enter the waiting state by the following ways:

- We can invoke sleep() method of the thread.
- An attempt to acquire the object’s lock can put the thread in waiting mode.
- We can also invoke wait() method of the thread.
- A thread can also be entered in waiting state by invoking its suspend() method.

What the difference is between notify and notify All methods?

- The notify will run only first thread which has called wait() on same object. i.e. the object which has called the wait() must be the same as the object that calls
- The notifyAll will run all threads which has called wait() on same object.
- While using notifyAll the highest priority thread will run first.

What is the difference between yielding and sleeping?

- Sleep causes the currently executing thread to sleep until the specified time is completed. The thread will resume once the specified time period is over.
- Sleep causes the currently executing thread to sleep and gives a chance to other threads to execute. The thread will join the ready queue.
- Thread.sleep() will moves the thread to “Wait” state.
- Thread.yield() will moves the thread to “Ready” state.

What is the difference between preemptive scheduling and time slicing?

- In Preemptive scheduling, highest priority task will executes until it enters in waiting or dead states. It also executes, until a higher priority task enters.
- In Time slicing, a task will execute for a fixed time slice and after that it will go in ready state.
- At that time the scheduler will find the executable task, according to the priority and various other tasks.
- In preemptive scheduling, the running task will be preempted by the higher priority task.
- In time slicing methods, a task executes until the specified period of time. Once the execution of that task is complete then the higher priority task will be executed if available.

What is thread synchronization?

- In multithreading, the shared resources are allocated to one thread at a time.
- The synchronization of allocating the shared resources between multiple thread ensuring that the shared resources will be allocated to only one thread at a time is called thread synchronization.
- The synchronized keyword is used to define the critical block in which every Java object get a lock to enter.

Syntax:
Synchronized(object) // object is reference of the object to be synchronized
{
   // statement to be synchronized.
}

? The synchronized keyword provides locking which maintain the mutual exclusive access of shared resource and race of objects for data.

What is volatile?

- When more than one threads access the same variable then each thread will maintain its own copy of that variable in the form of local cache.
- When a thread is changing the value of variable, it is actually changing the local cache not the main variable memory.
- Every thread which is using the same variable doesn’t know anything about the values changed by another thread.
- To overcome this problem, if you declare a variable as volatile, then whenever a thread is changing the value of a volatile, it is actually changing to the main memory. So, all other threads which are accessing the same variable can get the changed value.

What is daemon thread and how it differs from user thread?

- A user thread is created by the application (user) while the daemon thread is created by the JVM to provide services to user threads.
- If user threads are exists then only daemon threads exists.
- You can make a user thread as daemon thread by using setDaemon(true) method.
- In an application when only daemon threads are running (i.e. no user thread is running) then JVM will shut down the application and subsequently stops all daemon threads.
- To keep the application running, at least one user thread should be running.

What is Thread leak?

- Thread leak is when application does not release references of the thread object and those threads do not get garbage collected.
- Number of such unused threads increases with time and it can cause issues in the application like long response time.

To overcome this problem we can do the following

1. By maintaining a log for all entry and exit point of thread.
2. Check how the new thread is created and how it is closed.
3. By using exception handling etc.

Explain the method of Thread class with example.

- In this method of creating thread, we have to extend the Thread class and override the run() method in our class to create a Thread.
- We have to create an object of the our class.
- Once the object is created then we have to invoke the start() method and it will generate a new thread of execution.

For example
public class MyThread extends Thread
{
   public void run()
   {
       // code to execute under the thread
   }
   public static void main(String [] args)
   {
       MyThread c = new MyThread();
       c.start();
   }
}

What are the different states of a thread's lifecycle?

Following are the different states of threads:

1. New – A thread is called in New state until the start() method is called for the object of that thread. The thread is not alive in this state.

2. Runnable – The thread is called in Runnable state after the start() method is called for the object of that thread. The thread may enter into the Runnable state from Running state. The thread is called alive in this state.

3. Running – The thread is called in Running state when the thread scheduler take it from the Runnable thread’s pool.

4. Waiting/Blocked/Sleeping – In these states the thread is alive but it’s not in Runnable state. A running thread is called in these states after wait() or sleep() method is called that thread or when the thread is blocked while waiting for I/O resources.

5. Dead – After the execution of run() method is complete then the thread is called in dead state. Once a thread is dead then it cannot be start again.

What is difference between thread and process?

- Process has its own memory address while the thread share the address of the process by which it is created.
- Thread can access the data segment of its process directly while processes can access their own copy of the data segment of its parent process.
- Threads have almost no overheads while processes may have overheads.
- We can create a new thread easily but to create new process we have to duplicate the parent process.
- If any changes in main thread are occurred it can affect the behavior of the other threads of the same process. While in case of process if any changes is occurred in parent process it won’t affect the behavior of parent process.
- The direct communication is possible between threads of same process while in case of same sibling processes only interprocess communication is possible.

What happens if we invoke run method without calling the start method for a thread instance?

- If we instantiate a thread it is called in new state until the Start() method is called.
- If we don't call a start() method for that thread instance, the thread is not called alive.
- If we invoke run method without calling the start method for a thread instance, the code in run() method wil not be executed by a new thread but it will be executed by the existing thread only.

What are the advantages or usage of threads in Java?

Following are the advantage of using threads in Java.

- Threads support concurrent operations. For example, Server can handle multiple requests coming from different clients by managing separate thread for each request.
- Threads often result in simpler programs. Updating of separate views can be managed by separate Thread to give continuous updates.
- Threads provide a high degree of control on application.
- Threading gives the concurrency in our application by simplified coding.
- Using threading, a computer with more than one CPU can execute multiple threads on different functional units without using time sharing.
- The cost of communication between threads is relatively low.

Explain the method of Runnable interface with example.

- In this method of creating thread, we have to implement the Runnable interface and implement the run() method in our class.
- We have to create an object of our class.
- Then we you have to pass the reference of that object for creating a new object of Thread
- Invoke the start method using this Thread object which will create a new thread of execution.

For example
public class MyThread implements Runnable
{
   public void run()
   {
       // code to execute under the thread
   }
   public static void main(String [] args)
   {
       MyThread c = new NewThread();
       Thread t = new Thread(c);
       t.start();
   }
}

What are the methods of the thread class used to schedule the threads?

The methods of the thread class used to schedule the threads are as follows:

- public final void join() throws InterruptedException
- public final void notify()
- public final void notifyAll()
- public static void yield()
- public final void setPriority(int priority)
- public static void sleep(long millis) throws InterruptedException
- public final void wait() throws InterruptedException

What is threadLocal variable?

If a variable is declared as threadLocal then all the thread which accesses that variable will maintain its own copy of variable and would not use the copy of any other thread.

For example let consider the scenario of giving JDBC connection to each thread.
public class ThreadLocal
{
   public Object get();
   public void set(Object myValue);
   public Object FirstValue();
}

//Implementation of ThreadLocal

public class ConnectionDispenser
{
   private static class ThreadLocalConnection extends ThreadLocal
   {
       public Object FirstValue ()
       {
           return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
       }
   }

   private static ThreadLocalConnection con = new ThreadLocalConnection();
   public static Connection MyConnection()
   {
       return (Connection) con.get();
   }
}

How do you debug your application for issues when multiple threads are being executed?

Following are some way to debug issues in multi-threaded applications in Java.

- By using logging and print statements along with thread names. In this way we can know about the flow of thread execution.
- With the use of debugging functionality available in Eclipse and JDeveloper.
- We can write a thread dump of the application which will give the information about the active threads at a point of time.

This is most effective way for detecting deadlocks in production systems.

What is deadlock?

- When two or more threads are waiting for each other and get blocked forever then this situation is called Deadlock.
- During deadlock two threads, each thread has acquired a lock on one resource and trying to acquire a lock on resource of other thread.
- Each thread will wait indefinitely for the other to release the lock, unless one of the user processes is stopped.

In terms of Java API, thread deadlock situation can arise in following conditions:

1. When two threads call Thread.join() on each other.
2. When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

What is starvation?

- Starvation is a situation when some threads acquired the shared resources for long time and therefore other threads are not able to access those resources and not able to do anything further.
- For example, suppose an object provides a synchronized method that often takes a long time to return.
- If one thread invokes this method frequently, other threads that also require frequent synchronized access to that object will be blocked.
- In Java, Starvation can be caused by inappropriate allocation of thread priorities.
- A thread with low priority can be starved by the threads of higher priority if the higher priority threads do not release shared resources time to time.
40 Javascript Interview Questions and Answers - Freshers, Experienced
Javascript interview questions and answers for both freshers and experienced - In this series, we have covered all about JavaScript and answered the questions that might be asked during an interview.
JavaScript vs. Jscript
Both JavaScript and Jscript are almost similar. Java script was developed by Netscape...
Difference between Client side JavaScript and Server side JavaScript
difference between Client side JavaScript and Server side JavaScript - ...
Post your comment
Discussion Board
Good Qns
Hi .. I found a couple of good questions here: http://knowledgesun.com/core-java-multithreading-interview-questions/ ,
sam 09-30-2014