Java Threads Interview Questions

What are Threads?

Threads are lightweight processes and have thier own stack memory but share the main memory of process which means all the threads of same process will share the memory of process.

What are three ways in which a thread can enter the waiting state?

Or

What are different ways in which a thread can enter the waiting state?

A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object’s lock
4. By invoking an object’s wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q3) How do different threads of same process communicates?

Threads within same process communicates via wait, notify methods of Java.

What are the different ways of creating thread?

Threads can be in  different ways-

  1. Extending Thread class.
  2. Implementing Runnable interface
  3. Using Thread Executor framework ( thread pool)

Which method needs to be implemented to make thread?

public void run()

Which method needs to be called in order to execute the thread?

start()

What will happen if a developer calls run() method instead of start() to execute the thread?

If we call run() method instead of start() then functionality will be executed in a main thread instead of spawning a new thread.

What are the different types of threads?

There are two types of threads –

a)daemon threads – threads which will be stopped automatically when main program ends.

b) non daemon threads- program will wait till all non daemon threads stops.

 

How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state?

Or

Extending Thread class or implementing Runnable Interface. Which is better?

You have two ways to do so. First, making your class “extends” Thread class. The other way is making your class implement “Runnable” interface. The latter is more advantageous, cause when you are going for multiple inheritance, then only interface can help. . If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class. Also, if you are implementing interface, it means you have to implement all methods in the interface. Both Thread class and Runnable interface are provided for convenience and use them as per the requirement. But if you are not extending any class, better extend Thread class as it will save few lines of coding. Otherwise performance wise, there is no distinguishable difference. A thread is in the ready state after it has been created and started.

What is mutual exclusion? How can you take care of mutual exclusion using Java threads?

Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What invokes a thread’s run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.

What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(), notify() and notifyAll() methods are used to provide an efficient way for thread inter-communication.

What is thread? What are the high-level thread states?

Or

What are the states associated in the thread?

A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

What is deadlock?

When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock.

How does multithreading take place on a computer with a single CPU?

The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Can Java object be locked down for exclusive use by a given thread?

Or

What happens when a thread cannot acquire a lock on an object?

Yes. You can lock an object by putting it in a “synchronized” block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.

What’s the difference between the methods sleep() and wait()?

The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex: sleep(1000), puts the thread aside for exactly one second. The wait method is used to put the thread aside for up to the specified time. It could wait for much lesser time if it receives a notify() or notifyAll() call. Ex: wait(1000), causes a wait of up to one second. The method wait() is defined in the Object and the method sleep() is defined in the class Thread.

What is the difference between process and thread?

A thread is a separate path of execution in a program. A Process is a program in execution.

What is daemon thread and which method is used to create the daemon thread?

Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon()

When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.

What do you understand by Synchronization?

Or

What is synchronization and why is it important?

Or

Describe synchronization in respect to multithreading?

Or

What is synchronization?

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}

When you will synchronize a piece of your code?

When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.

Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

What is an object’s lock and which objects have locks?

Answer: An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.

What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

How would you implement a thread pool?

public class ThreadPool implements ThreadPoolInt

This class is an generic implementation of a thread pool, which takes the following input

a) Size of the pool to be constructed

b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.

This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.

Is there a separate stack for each thread in Java?

Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information about a method like local variables.

What is the default type of threads?

Default threads are non-daemon. By default thread type will be same as the thread which has initiated it and main thread is non-daemon so all the threads are by default non-daemon.

How to create a daemon threads?

We can call setDaemon(true)  method on thread object to make it daemon.

What is the default thread naming conventions?

JVM  uses "Thread-number" format as a thread name. Alternatively we can use setName() method on thread instance to assign a meaningful name to thread.

What will happen if we start already started thread?

Once a thread is started, it cannot be started again. Doing so will throw IllegalThreadStateException at runtime.

What are the different methods of thread class?

Answer- There are four methods-

  • public static void yield()
  • public static void sleep(long millis) throws InterruptedException
  • public final void join() throws InterruptedException
  • public final void setPriority(int newPriority)

Explain the states of a thread?

Broadly there can be below five states of a thread-

  1. New – When a thread is instantiated by calling new keyword. (prior calling of start method)
  2. Dead- Thread has completed its functionality.
  3. Runnable- Thread is ready to run but waiting for CPU. (start method has been called). Thread can never go to running state from new or waiting /blocking state.
  4. Running- Thread is running
  5. Waiting/ Blocking or Sleeping-  thread is either waiting for the resources or is being blocked and will go back to runnable state

Explain thread’s sleep method?

Thread sleep method is used to slow down the thread’s processing. This method takes a time in milli seconds for which it will be minimum delayed. I mentioned “minimum” because after the specified time, thread will go back to runnable state and not running state.

One important point to remember is that a thread cannot make another thread sleep. It can only sleep itself as sleep is a static method.

Explain thread’s sleep method?

 Thread sleep method is used to slow down the thread’s processing. This method takes a time in milli seconds for which it will be minimum delayed. I mentioned “minimum” because after the specified time, thread will go back to runnable state and not running state.

One important point to remember is that a thread cannot make another thread sleep. It can only sleep itself as sleep is a static method.

Explain Thread priorities?

 Every thread is assigned a default priority when it is created and priorities are used internally to decide which thread will be given preference but our code should not rely much on thread priorities. We can set thread priority by calling setPriority() method. Priorities can be set between 1 to 10 and default is 5. Java provides below three constants.

  • Thread.MIN_PRIORITY – value is 1
  • Thread.NORM_PRIORITY – value is 5
  • Thread.MAX_PRIORITY – value is 10

How we can know the priority of a thread?

We can call getPriority() method on a thread instance.

Explain yield method of thread?

yield method is similar to sleep with the difference is that thread voluntarily goes back to runnable state from running and letting other thread to run. This method may not be effective and it might happen that same thread is again moved back to running from runnable. One important point to remember is that a thread cannot make another thread to yield. It can only yield itself as yield is a static method.

What is the use of join() method of thread?

Sometime threads are dependents and one thread requires another thread to complete its functionality before it proceeds. In such scenarios-  a thread can call join() method of another thread instance on which it is dependent. In other words say T1 and T2 are two threads and at some point of T1, it becomes dependent on T2 so T1 thread can call T2.join() so T1 will wait till T2 completes.

Which class defines wait(), notify()  and  notifyAll() methods?

These methods are defined in Object class because every object can have a lock.

Which class defines wait(), notify()  and  notifyAll() methods?

These methods are defined in Object class because every object can have a lock.

What is important point to know about wait and notify?

Calling wait() will immediately release the lock but notify will release lock once its thread completes the synchronized block.

How many locks are possible on an Object?

There is only one lock available per object which is acquired by the thread when it comes in synchronization context.

Explain synchronization?

Synchronization is very important feature when it  comes to multi threading environments. When one thread is inside the synchronization block then no other thread can go inside any synchronization block having a lock on same object. Synchronization can be applied on methods in which lock will be applied to current instance. Synchronizations can even be applied on blocks in which only a piece of method will be synchronized. In this case we need to pass an object on which lock will be applied.

What is the difference between synchronization blocks or synchronized method?

It is better to use synchronized blocks over synchronized method if only a piece of code need to be thread safe to get a better performance.

Can we have a both synchronized and non synchronized methods in a class?

Yes 

Can one thread acquires multiple locks? If yes how?

Yes a thread can acquire multiple locks. Think of the scenario where a thread is in synchronized block (means have a lock on one object) and then from this synchronized method it calls another synchronized method of another object.

Like us on Facebook