Java Thread Interview Questions and Answers

    6 Votes

Frequently asked Advanced Java Thread and Java Exceptions Interview Questions and Answers for 2-6 year experienced Java developers, Senior software engineers, Tech Lead and freshers.

1) What is meant by Thread ?

A thread is a path of execution of a Program. A Thread is a sequence of instructions that executed in a predefined unique flow of control. Advantages of thread are

  • Reduces development time
  • Reduces maintenance costs
  • Improves the performance of complex applications
  • Useful for improving the responsiveness of the user interfaces
  • Used in server applications for improving high throughput and resource utilization

2) Explain Thread Life Cycle ?

Thread Life cycle have four states as below

  • New - While thread is initialized, it will enter to init state. After initialization, we should call start() method. If start method is not called, java throws IllegalThreadStateException. 
  • Runnable - Once a start method is called then it will enter to runnable state. Resources and schedules associated with the thread is allocated by start method. Then it will call run() method.
  • Not Runnable  
    • sleep() - Wait for specified time
    • wait() - Wait until notify.
    • suspend() - Blocked by another thread
  • Dead - if the run method gets completed or thread object is assigned a null value, its enter into dead state.
 

3) What are the differences between Thread and process ?

ProcessThread
It has own address. Share the address space of the process.
It has their own copy of the data segment of the parent process. It have direct access to the data segment of its process.
It must use interprocess communication to communicate with sibling processes. Threads can directly communicate with other threads of its process
Changes to the parent process do not affect child processes. Changes to the main thread like cancellation or change in priority of thread may affect the behaviour of the other threads of the process

4) Is it possible to restart the dead Thread in Java ?

No. A thread can't be restarted once the execution is completed.

5) Can you explain about Synchronized keyword in Java ?

When 2 or more threads try to access a shared object, Java throws thread interference and memory consistency errors. To overcome this scenario, we need to synchronize java objects using Synchronized keyword. We can use synchronize keyword in 

  • Used in method - public void synchronized method { // access code}
  • Used in block - synchronized(obj) { // access code}


6) How object are communicate with each other in synchronized context ?

In all the classes, final methods like wait, notify and notifyAll has been implemented. All three methods can be called only from within a synchronized context. Using these methods object are communicated with each other in synchronized context.

7) What is the difference between sleep() and wait() ?

Sleep()Wait()
Thread stops working for the specified duration. Thread stops working until the object in waiting is notified.
Thread method. Object method
It doesn’t release the lock while waiting. It releases lock on object while waiting.
Put thread on sleep It is normally done on condition.

8) How to stop a running thread in Java ?

Thread will stop once come out of run method.  So one of the way to stop a thread as follows

public class MyThread extends Thread {
 @Override
 public void run() {
    while (!this.isInterrupted()) {
    }
  }
}
// To stop a thread, call method interrupt():
myThread.interrupt();

9) What is the difference between notify() and notifyAll() ?

notifynotifyAll
Used to wake up a single thread All threads in wait state wakes up.


10) What is meant by Daemon threads in Java ?

Daemon Thread is different from user created threads. It is created by the JVM for executing internal operations like garbage collection. When a non daemon thread stops execution, JVM exits all the daemon threads currently under operation without waiting for their activities to complete. To make a Daemon thread, use code Thread.setDaemon(true).

11) What is difference between threadObject.run() and threadObject.start() in Java ?

StartRun
When program calls start() method, JVM creates a new Thread is created and code inside run method is executed inside in that thread. In case, we are calling the run() method directly, JVM won't create a new thread. Code specified inside the run method will get execute on current Thread.
Cannot call start() method twice on thread object. Can call run method more than once.


12) Can run() method take arguments ?

No : We can't pass arguments to the run() method, which is  defined inside the Runnable interface.

Yes : We can create an overloaded method of run() with arguments. But when a thread is started, JVM will always call the run method without arguments.


13) Can a class extend Thread class, without overriding run() method? What will happen if I call threadObject.run() ?

Case 1 : If you extend Thread class, it is not mandatory to override run method. But if you want to start over a new thread from there on in the code, then it is mandatory to override run().

Case 2 : If you are implementing Runnable interface, then it is mandatory to override run() so that the program would compile without any errors. It also helps you to start over a new thread from there.


14) Can you explain about join() in Thread class ?

join() causes the main thread to wait until the child thread completes it's execution. It is also a blocking method, which blocks the main thread until thread on which join has called die or specified waiting time is over.


15) Can you explain about the thread scheduler?

The entire responsibility of maintaining the sequence of execution of threads, where which thread should be given first preference than the other, lies with the thread scheduler. The scheduling depends on the algorithm of the scheduler. Many types of algorithms exist like preemptive and time slicing with round robin etc.


16) Can you explain about context switching in threads ?

  • A context switch is the switching of the CPU from one process/thread to another. 
  • It perceives the threads or tasks as running at the same time.
  • Most context switching is caused by external interrupts.


17) What are the method available in java.lang.object class and java.lang.Thread class ?

Object :

public final void wait() throws Interrupted exception 
public final void notify()
public final void notifyAll()

Thread:

public final void setPriority(int priority) 
public void start()
public void run()
public static void sleep(long millis) throws Interrupted exception
public final void join()
public void interrupt()
public static void yield()
public void resume()


18) Can you give ,real time example of multi-threaded application ?

FTP application : Transfer and download multiple files simultaneously using multi threading.



19) What is meant by Deadlock ?

Deadlock arises when two threads get the same set of locks. But the order of locks is different. As a result of this, the first thread will be waiting for the second thread to release the lock, meanwhile second thread is waiting for the first thread to release the lock. As a result of this, both threads will in a suspended state. Synchronization should be used to avoid Deadlock.


20) What is race condition in Java ?

A race condition is a situation, when two threads access the same location in memory at the same time, and at least one of the accesses is a write.


21) Can you explain about Static method Synchronization and Instance method synchronization?

Locks applied on the static method and non static methods are different. Locks are applied on the class in case of static methods. In case of non-static methods, locks are applied on the instance of the class. For better understanding, look at the example below

Static method Synchronization :

static synchronized void mymethod()
{
  Test();
}

equivalent to

static void mymethod()  
{
 synchronized(MyClass.class)
 {
   Test();
 }
}

Instance method synchronization :

synchronized void mymethod()
{
  Test();
}
equivalent to

void mymethod()
{
   synchronized(this)
   {
     Test();
   }
}

22) Differentiate Exception and error in Java ?

ExceptionError
Derived from java.lang.Exception Derived from java.lang.Error
Indicates conditions that an application might catch. Indicates serious problems that an application should not catch
Ex: FileNotFoundException. Ex: OutOfMemoryError

23) Checked vs Unchecked Exceptions in Java ?

Checked ExceptionsUnchecked Exceptions
Checked at compile time. Checked at runtime
Method must either handle the exception or it must specify the exception using throws keyword. Error and RuntimeException classes are unchecked exceptions.
Expected to recover from an exception. It cannot do anything to recover from the exception.
Ex: FileNotFoundException. Ex: ArithmeticException

24) Can you explain difference between Throws and Throw ?

ThrowThrows
Used to declare an exception. Used to throw an exception explicitly
Throw is followed by an instance variable Throws is followed by exception class name
Throw is used inside method body to invoke an exception. Throws clause is used in method declaration
Cannot throw more than one exception Can declare multiple exceptions.
Ex: throw new Exception("Something went wrong!"); Ex : public void mathFunction() throws IOException,ArithmeticException

25) Can you explain about finally keyword in Java ?

  • Finally is used for exception handling along with try and catch.
  • The code in finally block will execute even if an exception occurs.
  • A finally block appears at the end of try or try-catch block.


26) Is it possible to have try block without finally and catch block ?

No. This will result in a compilation error. A try block must be followed by a catch or a finally block. We can avoid catch or the finally block, but not both.


27) Can you explain about situation where getting a compilation error exception already caught ?

When we specify multiple catch statements, make sure that the most specific one is put on top,followed by more generic ones at the end. If you put the more generic ones at the beginning, an exception will be caught multiple times and hence getting a compilation error "exception already caught".


28) Can you explain about Exception handler in Java ?

Java have powerful Exception handling. The try-catch-finally block is used to handle the exception.

try // The code in which the exception may occur is enclosed in a try block
{
}
catch(Exception e) // The catch clause matches a specific exception to a block of code which handles that exception.
{
}
finally // Clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block
{
}

Throw : Used to declare an exception.

throw new Exception("Something went wrong!");

Throws : Used to throw an exception explicitly.

public void mathFunction() throws IOException,ArithmeticException

29) Can you explain about java.lang.RuntimeException class ?

Exceptions that happen at runtime due to programming errors is called RuntimeException. It will be good, if the programmer checks for this exception during code review. If we want to handle run time exception in each and every code block, clarity of program will be reduced drastically. Ex: Arithmetic exceptions, such as dividing by zero

30) Can you explain about java.lang.throwable class ?

All the errors and exception handling classes in Java are derived from super class "java.lang.Throwable". JVM throws exception created by Throwable class objects or it's subclass objects.


31) Can you explain the exception class hierarchy ?

Main exception class is Throwable. Other classes that inherit Throwable class are Checked exceptions and Unchecked Exceptions.


32) Can you explain about IndexOutOfBoundExecption classes and it sub classes ?

It's under RuntimeException. Two classes that inherit IndexoutOfBoundException are "StringIndexOutOfBoundsException" and "ArrayIndexOutOfBoundsException".


33) Can you explain about OutOfMemoryError ?

OutOfMemoryError is a serious problem created by the memory limitation of the machine. In some cases, programming errors cause memory leak and in turn creates "OutOfMemoryError". Whatever be the reason for memory shortage, when the JVM is not able to create and object or garbage collector is not in a position to release memory, out of memory error is thrown.


34) Can write a program to create manual exception class ?

To create you own exception extend the Exception class or any of its subclasses.

class FirstException extends Exception { }


35) How to avoid NullPointerException in java ?

NullPointerException is an unchecked exception. Code to handle exception is as shown below

Object mayBeNullObj = getTheObjectItMayReturnNull();

if (mayBeNullObj != null) { // to avoid NullPointerException
   mayBeNullObj.workOnIt();
}

Popular Videos

communication

How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Java OOPS Interview Questions and Answers
Java Interview Questions
Top Advanced Java Interview Questions and Answers
Java Collections Interview Questions and Answers