Threading Interview Questions in Java

We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on Threading

Question 1.
What do you understand by multithreading?
Answer:
Java has built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each such part is called a thread, and each thread defines a separate path of execution. A text editor formatting its text and printing at the same time is a good example of multithreading. In this way, we see that multithreading is a specialized version of multitasking.

Question 2.
Can multithreading lead to problems at times?
Answer:
Multithreading can lead to problems at times especially when you create too many threads. In such a case, you actually degrade the performance of your program rather than enhance it as multithreading is supposed to do. This is because some overhead is always associated with context switching. If you create too many threads, more CPU time will be spent changing contexts rather than executing your program! You must always remember and be aware of this vital fact.

Question 3.
What is the use of the isAlive( ) method?
Answer:
How can one thread know when another thread has ended? You can call isAlive( ) on the thread. This method is defined by Thread, and its most general form is as follows:-

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running and false otherwise.

Question 4.
What is the use of the join( ) method?
Answer:
There is a second way to know when a thread has ended apart from the isAlive( ) method described above in Q. 229. While isAlive( ) is occasionally useful, the method, which you will more often use to wait for a thread to finish is called join(), whose most general form is as follows:-

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates/finishes. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Apart from the form of joint) elaborated above, there are additional forms, which allow you to specify the maximum amount of time that you want to wait for the specified thread to terminate/finish.

Question 5.
What do you mean by a deadlock?
Answer:
There is a special type of error relating specifically to multitasking that you need to avoid. It is known as a deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects.

Question 6.
Can the thread priority be changed? What is the default priority assigned to a thread?
Answer:
The thread priority can indeed be changed ranging from a minimum one to a maximum one; the default priority assigned to a thread is 5.

Question 7.
Elucidate the daemon thread.
Answer:
A continuously executing thread such as the one providing background processing (e.g. the garbage collector thread) is referred to as a daemon thread; daemon threads act as service providers for other objects/threads.

Question 8.
Explain the thread lifecycle.
Answer:
A thread: is created using the new Thread( ) statement
is executed using the start( ) method
now, enters the ‘runnable state’
when blocked on I/O or when wait()/sleep( ) methods are used, enters ‘not runnable state’
comes back into a ‘runnable state’ continuing to run/execute the statements
finally, ‘dies’ after coming out of the run( ) method
ALL THE AFOREMENTIONED TRANSITION STATES OF A THREAD ARE REFERRED TO AS ITS LIFECYCLE (Figure 3).

THREADING Interview Questions in Java chapter 4 img 1

Question 9.
What do you understand by a monitor?
Answer:
A monitor is a lock on an object which allows only one thread to access or modify the contents of that object.

Question 10.
How can you make code thread-safe?
Answer:
The keyword ‘synchronized’ is used to temporarily lock an object to have exclusive access to it. It marks a block of code or an entire method as a critical section. Only one thread can execute at any point in time. Other threads will wait for their turn to use the critical section.

When an instance method is synchronized, the synchronized code can be run by many threads on different objects simultaneously, since the locking is on the object. For a synchronized class method, the locking is on the class object, which thus limits to only one thread executing that particular code.

Question 11.
What is the purpose behind Thread. wait( )?
Answer:
Thread.wait( ) and Thread. notify( ) methods are used for inter-thread communication.
Thread. wait( ) makes the thread go to sleep until some other thread wakes it up using the Thread.notify( ) method.

Question 12.
Bring out the difference between Thread. notify( ) and Thread. notifyall ( ).
Answer:

Thread. notify( ): This method can only be called from within a synchronized
method/block. It wakes up a single thread that is waiting on the object’s lock. In case there is more than one thread waiting, the choice is arbitrary, i.e. there is no particular way to determine which of the waiting threads should be awakened.

Thread.notifyAll( ): This method wakes up all the waiting threads. In the JVM the scheduler then decides which of the awakened threads will execute.

Question 13.
How do you invoke a thread’s run( ) method?
Answer:
After a thread is started through its start( ) method or that of the Thread class, the JVM scheduler invokes the thread’s run() method once the turn comes for this thread to run/ execute.

Question 14.
Can you elucidate the concept of thread synchronization?
Answer:
Two threads are said to be synchronized if while the first one is acting on an object, the second one doesn’t act on that object and while the second one acts on an object, the first one doesn’t act on that object. This concept of thread synchronization is especially handy in multithreading.

Question 15.
Differentiate between a ‘synchronized block’ and the ‘synchronized’ keyword.
Answer:
While a ‘synchronized block’ synchronizes a block of statements, the ‘synchronized’ keyword is used to synchronize a complete method.

Question 16.
Differentiate between sleep( ) and wait( ).
Answer:
Both of these methods are used to suspend thread execution for a specified period. But, when sleep( ) is executed inside a synchronized block, the object continues to be under lock;
on the other hand, when wait( ) is executed inside a synchronized block, the lock is removed. In general, sleep( ) is used to make a thread wait for some time while wait( ) is used alongside notify( ) / notifyAll( ) in multithreading.

Question 17.
Does the thread execute any method by default; if yes, which one?
Answer:
Yes, it does! The public void run() method.

Question 18.
Differentiate between “implements Runnable” and “extends Thread”
Answer:
Functionally, both of them are the same but by using “extends Thread”, we cannot extend another class since Java doesn’t support multiple inheritances; on the other hand, if we use “implements Runnable”, we can still extend another class; This feature is especially handy when we want to use threads as well as access the characteristics of another class.
class class1 extends Thread, class2                        // not okay
class class1 extends class2 implements Runnable // okay

Question 19.
Can you stop a thread in Java; if yes, how?
Answer:
Yes, it is indeed possible to stop a thread in Java. This can be achieved by creating a boolean type variable that is initialized to ‘false’ and later on when we want to stop the thread, we should make its value ‘true’; the status of this variable is checked in the run() method and since it is true, the thread executes the return statement and then stops executing.

Question 20.
Which is the thread that always runs in a Java program by default?
Answer:
The main thread.

Question 21.
In how many ways can you create a thread? Elaborate.
Answer:
There are essentially two ways of creating a thread:-

(1) The first method involves extending the Thread class. This should only be done in case the class doesn’t need to be extended from another class.

import java. lang.*;
public class Cntr extends Thread
{
      public void run( )
      {...............}
}

Here, a new class Cntr is being created that extends the Thread class and overrides the Thread. run( ) method. The run( ) method is where all the work of the Cntr class thread is being done.

(2) The second way involves implementing the interface Runnable.

import java. lang.*;
public class Cntr implements Runnable
{
      Thread T;
      public void run( )
     {....................}
}

In this case, the abstract method run( ) is defined in the Runnable interface and is being implemented. Note that we have an instance of the Thread class as a variable of the Cntr class.

The only difference between the two methods is that by implementing Runnable, there is greater flexibility in the creation of the class Cntr, i.e. there still is an opportunity to extend the class Cntr, if needed.

Question 22.
What is the purpose of Thread. start( )?
Answer:
Thread. start( ) creates the system resources necessary to run the thread and schedules it to run. After the start method has returned, the thread is actually in the Runnable state. When a thread gets the CPU time, it will be executed.

Question 23.
Explain the concept of thread prioritization.
Answer:
Execution of multiple threads on a single CPU, in some order, is called scheduling. The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling. This algorithm schedules threads based on their priority relative to other runnable threads.

When a java thread is created, it inherits its priority from the thread that created it. A thread’s priority can also be modified at any time after its creation using the setPriority( ) method.

Thread, priorities are integers ranging between MIN_PRIORITY (1) and MAX__PRIORITY (10). The value 5 is the default priority. The greater the integer, the higher the priority of the corresponding thread.

At any given time, when multiple threads are ready to be executed, the java runtime system chooses the runnable thread with the highest priority for execution. Only when that thread stops, yields, or becomes not runnable for some reason will a lower priority thread start executing.

If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them in a round-robin fashion. The chosen thread will run until a higher priority thread becomes runnable, or, it yields (or, its run method exits), or, its time allotment has expired (on systems that support time-slicing). Then, the second thread is given a chance to run, and so on, until the interpreter exits.

Java runtime system’s thread scheduling algorithm is preemptive as well. Thus, if at any time, a thread with a higher priority than all other runnable threads becomes runnable, the runtime system chooses the new higher priority thread for execution. This new higher priority thread is said to have preempted the other threads.

Question 24.
Bring out the difference between yield( ) and sleep( ) methods.
Answer:
When a thread invokes its yield() method, it returns to its ready state. On the other hand, when a thread invokes its sleep( ) method, it returns to its waiting state.

Question 25.
Bring out the difference between preemptive scheduling and time slicing.
Answer:
Under preemptive scheduling, the highest priority thread executes until it enters its waiting or dead states or a higher priority thread comes into existence. On the other hand, under time slicing, a thread executes for a predefined slice of time and then re-enters the pool of ready threads. The scheduler then determines which thread should execute next, based upon priority and other factors.

Question 26.
Explain in brief the concepts of synchronized methods and synchronized statements.
Answer:
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.

This means that no other thread can access the object till the current thread releases the object. This is used to make the code thread-safe and prevent dirty reads.

Question 27.
Linder, what condition(s) do you use synchronized statements?
Answer:
Synchronized statements are good to use in two cases:-
(1) It is sufficient to synchronize only part of a method, e.g.

void mthd( )
{
     // some statement
     Synchronized( this)
     {
          this.x = 100;
     }
         // some statement
}

(2) If a class whose object to be locked is part of a third part jar file, e.g.

void mthd( )
{
      // some statement
      Synchronized(thirdPa rty Object)
      {
         thirdParlyObject.x = 100;
      }
      // some statement
}

Question 28.
Can you restart a dead thread; if yes, how?
Answer:
A dead thread cannot be restarted.

Question 29.
Under what condition(s) does a thread go out of the runnable state?
Answer:
A thread becomes Not Runnable when one of the following events occurs:-

  1. Its sleep method is invoked.
  2. The thread is blocking on Input/Output.
  3. The thread calls the wait method to wait for a specific condition to be fulfilled.