Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What is the purpose of the finalize() method?

Answer»

Finalize() method is BASICALLY a method of Object class specially used to perform cleanup OPERATIONS on unmanaged resources just before garbage collection. It is not at all INTENDED to be called a normal method. After the complete EXECUTION of finalize() method, the object gets DESTROYED automatically.

2.

Can two threads execute two methods (static and non-static concurrently)?

Answer»

YES, it is possible. If both the THREADS acquire LOCKS on different objects, then they can EXECUTE concurrently without any problem.

3.

How do threads communicate with each other?

Answer»

Threads can COMMUNICATE USING three METHODS i.e., wait(), notify(), and NOTIFYALL().

4.

Explain volatile variables in Java?

Answer»

A volatile VARIABLE is basically a keyword that is used to ensure and ADDRESS the visibility of changes to VARIABLES in multithreaded programming. This keyword cannot be used with classes and methods, INSTEAD can be used with variables. It is simply used to achieve thread-safety. If you mark any variable as volatile, then all the threads can read its value directly from the main MEMORY rather than CPU cache, so that each thread can get an updated value of the variable.

5.

Explain the meaning of the deadlock and when it can occur?

Answer»

Deadlock, as the name SUGGESTS, is a situation where MULTIPLE threads are BLOCKED FOREVER. It generally occurs when multiple threads HOLD locks on different resources and are waiting for other resources to complete their task.

The above diagram shows a deadlock situation where two threads are blocked forever.  Thread 1 is holding Object 1 but needs object 2 to complete processing whereas Thread 2 is holding Object 2 but needs object 1 first. In such conditions, both of them will hold lock forever and will never complete tasks.

6.

What do you mean by garbage collection?

Answer»

Garbage collection is basically a process of MANAGING memory AUTOMATICALLY. It uses several GC algorithms among which the popular one includes Mark and Sweep. The process includes THREE phases i.e., marking, deletion, and compaction/copying. In simple words, a garbage COLLECTOR finds objects that are no longer required by the program and then DELETE or remove these unused objects to free up the memory space.

7.

What’s the purpose of the join() method?

Answer»

join() method is generally used to pause the EXECUTION of a current THREAD UNLESS and until the specified thread on which join is called is dead or COMPLETED. To stop a thread from running until another thread gets ended, this method can be used. It joins the start of a thread execution to the end of another thread’s execution. It is CONSIDERED the final method of a thread class.

8.

Explain thread pool?

Answer»

A Thread pool is simply a collection of pre-initialized or worker threads at the start-up that can be used to execute TASKS and put back in the pool when completed. It is referred to as pool threads in which a group of fixed-size threads is created.  By REDUCING the number of application threads and managing their lifecycle, one can mitigate the issue of performance using a thread pool. Using threads, performance can be enhanced and better system stability can occur. To create the thread POOLS, java.util.concurrent.Executors class USUALLY provides FACTORY methods.

9.

What is the start() and run() method of Thread class?

Answer»

start(): In simple words, the start() method is used to start or begin the EXECUTION of a NEWLY created THREAD. When the start() method is called, a new thread is created and this newly created thread executes the task that is kept in the run() method. One can call the start() method only once.  

run(): In simple words, the run() method is used to start or begin the execution of the same thread. When the run() method is called, no new thread is created as in the case of the start() method. This method is executed by the CURRENT thread. One can call the run() method multiple times. 

10.

What is Runnable and Callable Interface? Write the difference between them.

Answer»

Both the interfaces are generally used to encapsulate tasks that are needed to be executed by another THREAD. But there are some DIFFERENCES between them as given below: 

Running Interface: This interface is basically available in Java right from the beginning. It is simply used to execute code on a concurrent thread.  
Callable Interface: This interface is basically a new one that was introduced as a part of the concurrency package. It addresses the limitation of RUNNABLE interfaces along with some major changes like generics, enum, static imports, variable argument method, etc. It uses generics to define the RETURN type of object.   

public interface Runnable { public abstract void run(); } public interface Callable<V> { V call() throws Exception; }

Runnable Interface vs Callable Interface

Runnable InterfaceCallable Interface 
It does not return any result and therefore, cannot throw a checked exception. It returns a result and therefore, can throw an exception.
It cannot be passed to invokeAll method. It can be passed to invokeAll method.
It was introduced in JDK 1.0.It was introduced in JDK 5.0, so one cannot USE it before Java 5. 
It simply belongs to Java.lang.It simply belongs to java.util.concurrent. 
It uses the run() method to define a task.It uses the call() method to define a task. 
To use this interface, one needs to override the run() method. To use this interface, one needs to override the call() method.
11.

Why wait(), notify(), and notifyAll() methods are present in Object class?

Answer»

We know that every object has a monitor that allows the thread to HOLD a lock on the object. But the thread class doesn't contain any MONITORS. Thread usually waits for the object’s monitor (lock) by calling the wait() METHOD on an object, and notify other threads that are waiting for the same lock using notify() or notifyAll() method.  Therefore, these three methods are CALLED on objects only and allow all threads to communicate with each that are CREATED on that object.

12.

What’s the difference between notify() and notifyAll()?

Answer»

notify(): It sends a NOTIFICATION and wakes up only a single thread instead of multiple threads that are waiting on the OBJECT’s MONITOR.

notifyAll(): It sends notifications and wakes up all threads and ALLOWS them to compete for the object's monitor instead of a single thread. 

13.

What are the wait() and sleep() methods?

Answer»

wait(): As the name suggests, it is a non-static METHOD that causes the current thread to wait and go to sleep until some other threads call the NOTIFY () or notifyAll() method for the object’s monitor (lock). It simply releases the lock and is mostly used for inter-thread communication. It is defined in the object class, and should only be called from a SYNCHRONIZED context. 

Example:  

synchronized(monitor) { monitor.wait(); Here Lock Is RELEASED by Current Thread }

sleep(): As the name suggests, it is a static method that pauses or stops the execution of the current thread for some specified period. It doesn’t release the lock while waiting and is mostly used to introduce pause on execution. It is defined in thread class, and no need to call from a synchronized context.  

Example:  

synchronized(monitor) { Thread.sleep(1000); Here Lock Is Held by The Current Thread //after 1000 MILLISECONDS, the current thread will wake up, or after we call that is interrupt() method }
14.

How can we create daemon threads?

Answer»

We can create DAEMON threads in java using the thread class setDaemon(true). It is used to mark the current thread as daemon thread or USER thread. isDaemon() method is generally used to check whether the current thread is daemon or not. If the thread is a daemon, it will return true otherwise it returns false.  
Example:   
Program to illustrate the use of setDaemon() and isDaemon() method. 

public class DaemonThread extends Thread { public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread"); } else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = NEW DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.START(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); } }

Output:  

t1 is Daemon thread t3 is Daemon thread t2 is User thread

But one can only call the setDaemon() method before start() method otherwise it will definitely throw IllegalThreadStateException as shown below:   

public class DaemonThread extends Thread {  public void run()  {  System.out.println("Thread name: " + Thread.currentThread().getName());  System.out.println("Check if its DaemonThread: " + Thread.currentThread().isDaemon());  }  public static void main(String[] args)  {  DaemonThread t1 = new DaemonThread();  DaemonThread t2 = new DaemonThread();  t1.start(); // Exception as the thread is already STARTED  t1.setDaemon(true);  t2.start();  } } 

Output:  

Thread name: Thread-0 Check if its DaemonThread: false
15.

What's the difference between User thread and Daemon thread?

Answer»

User and Daemon are basically two types of thread used in JAVA by using a ‘Thread Class’.  

User Thread (Non-Daemon Thread): In Java, user THREADS have a specific LIFE cycle and its life is independent of any other thread. JVM (Java Virtual Machine) waits for any of the user threads to complete its tasks before TERMINATING it. When user threads are finished, JVM terminates the whole program along with associated daemon threads. 

Daemon Thread: In Java, daemon threads are basically REFERRED to as a service provider that provides services and support to user threads. There are basically two methods available in thread class for daemon thread: setDaemon() and isDaemon(). 

User Thread vs Daemon Thread

User ThreadDaemon Thread 
JVM waits for user threads to finish their tasks before termination. JVM does not wait for daemon threads to finish their tasks before termination.
These threads are normally created by the user for executing tasks concurrently. These threads are normally created by JVM.
They are used for critical tasks or core work of an application. They are not used for any critical tasks but to do some supporting tasks.
These threads are referred to as high-priority tasks, therefore are required for running in the foreground. These threads are referred to as low priority threads, therefore are especially required for supporting background tasks like garbage collection, releasing memory of unused objects, etc. 
16.

What’s the difference between class lock and object lock?

Answer»

CLASS Lock: In java, each and every class has a UNIQUE lock usually referred to as a class level lock. These locks are achieved using the keyword ‘static synchronized’ and can be used to make static data thread-safe. It is generally used when ONE wants to prevent multiple threads from ENTERING a synchronized block. 

Example:  

PUBLIC class ClassLevelLockExample { public void classLevelLockMethod() { synchronized (ClassLevelLockExample.class) { //DO your stuff here } } }

Object Lock: In java, each and every object has a unique lock usually referred to as an object-level lock. These locks are achieved using the keyword ‘synchronized’ and can be used to protect non-static data. It is generally used when one wants to synchronize a non-static method or block so that only the thread will be able to execute the code block on a given instance of the class.  

Example:  

public class ObjectLevelLockExample { public void objectLevelLockMethod() { synchronized (this) { //DO your stuff here } }}
17.

What's the difference between thread and process?

Answer»

Thread: It simply refers to the smallest UNITS of the PARTICULAR process. It has the ability to execute different parts (referred to as thread) of the program at the same time.  

Process: It simply refers to a program that is in execution i.e., an active program. A process can be handled using PCB (Process Control Block). 

ThreadProcess
It is a subset of a subunit of a process.It is a program in execution containing multiple threads.
In this, inter-thread communication is faster, LESS expensive, easy and efficient because threads share the same memory address of the process they belong to. In this, inter-process communication is slower, expensive, and complex because each process has different memory space or address.,
These are easier to create, lightweight, and have less overhead. These are difficult to create, heavyweight, and have more overhead.
It requires less time for creation, termination, and context switching.It requires more time for creation, termination, and context switching.
Processes with multiple threads use fewer resources.Processes without threads use more resources.
Threads are parts of a process, so they are dependent on each other but each thread executes independently.Processes are independent of each other.
There is a need for synchronization in threads to avoid UNEXPECTED scenarios or problems.There is no need for synchronization in each process.
They share data and information with each other. They do not share data with each other. 
18.

What are the two ways of implementing thread in Java?

Answer»

There are basically two ways of IMPLEMENTING thread in java as GIVEN below: 

  • Extending the Thread class

Example:

class MultithreadingDemo extends Thread { public VOID RUN() { System.out.println("My thread is in running state."); } public static void main(String args[]) { MultithreadingDemoobj=new MultithreadingDemo(); obj.start(); } }

Output:

My thread is in running state.
  • Implementing Runnable interface in Java

Example:  

class MultithreadingDemo implements Runnable { public void run() { System.out.println("My thread is in running state."); } public static void main(String args[]) { MultithreadingDemo obj=new MultithreadingDemo(); Threadtobj =new Thread(obj); tobj.start(); } }

Output: 

My thread is in running state.
19.

What is Thread in Java?

Answer»

Threads are basically the lightweight and smallest unit of processing that can be managed independently by a scheduler. Threads are REFERRED to as PARTS of a process that simply let a program EXECUTE efficiently with other parts or threads of the process at the same time. Using threads, one can perform complicated tasks in the easiest way. It is CONSIDERED the SIMPLEST way to take advantage of multiple CPUs available in a machine. They share the common address space and are independent of each other. 

20.

What are the benefits of using Multithreading?

Answer»

There are various benefits of multithreading as GIVEN below:

  • Allow the program to run continuously even if a part of it is blocked. 
  • Improve performance as compared to traditional parallel programs that use MULTIPLE processes. 
  • Allows to write effective programs that UTILIZE maximum CPU time
  • Improves the responsiveness of complex applications or programs. 
  • Increase use of CPU resources and reduce costs of maintenance. 
  • Saves time and parallelism TASKS
  • If an exception occurs in a single thread, it will not affect other THREADS as threads are independent. 
  • Less resource-intensive than executing multiple processes at the same time.