Java Multithreading and Concurrency Interview Questions

1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Multithreading is used to obtain the multitasking. It consumes less memory and gives the fast and efficient performance. Its main advantages are:

Threads share the same address space.
A thread is lightweight process.
The cost of communication between two processes is low.
.
Play

Next
Mute
Current Time
0:46
/
Duration
18:10

Fullscreen

Backward Skip 10s

Play Video

2) What is the thread?
A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in a different stack frame. A process may contain multiple threads. Threads share the process resources, but still, they execute independently.

.
3) Differentiate between process and thread?
There are the following differences between the process and thread.

A Program in the execution is called the process whereas; A thread is a subset of the process
Processes are independent whereas threads are the subset of process.
Process have different address space in memory, while threads contain a shared address space.
Context switching is faster between the threads as compared to processes.
Inter-process communication is slower and expensive than inter-thread communication.
Any change in Parent process doesn’t affect the child process whereas changes in parent thread can affect the child thread.
Java Multithreading

4) What is the purpose of the wait() method in Java?
The wait() method is provided by the Object class in Java. It is used for inter-thread communication. The java.lang.Object.wait() method is used to pause the current thread, and wait until another thread does not call the notify() or notifyAll() method. Its syntax is given below.

public final void wait()

5) What do you understand by inter-thread communication?
The process of communication between synchronized threads is termed as inter-thread communication.
Inter-thread communication is used to avoid thread polling in Java.
The thread is paused running in its critical section, and another thread is allowed to enter (or lock) in the same critical section to be executed.
It can be achieved by using the wait(), notify(), and notifyAll() methods.

6) What are the advantages of multithreading?
Multithreading programming has the following advantages:

Multithreading allows an application/program to be always reactive for input, even already running with some background tasks.
Multithreading allows the faster execution of tasks, as threads execute independently.
Multithreading provides better utilization of cache memory as threads share the common memory resources.
Multithreading reduces the number of the required server as one server can execute multiple threads at a time.

7) Why wait() method must be called from the synchronized block?
We must call the wait() method otherwise it will throw java.lang.IllegalMonitorStateException exception. Moreover, we need wait() method for inter-thread communication with notify() and notifyAll() method. Therefore, it must be present in the synchronized block for the proper and correct communication.

8) Explain lifecycle of a Thread?
A thread can have one of the following states during execution:

New: In this state, a Thread class object is created using a new operator, but the thread is not alive. Thread does nott start until we call the start() method.

Runnable: In this state, the thread is ready to run after calling the start() method. However, the thread is not yet selected by the thread scheduler.

Running: In this state, the thread scheduler picks the thread from the ready state, and starts running.

Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other thread to finish.

Dead/Terminated: A thread is in terminated or dead state, if it satisfies any of the following condition:

If it exits normally. It happens when the code of the thread has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.
Java thread life cycle
9) What is the difference between preemptive scheduling and 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 re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

10) What is context switching?
In Context switching the state of the process (or thread) is stored so that it can be restored and execution can be resumed from the same point later. Context switching enables the multiple processes to share the same CPU.

11) Differentiate between the Thread class and Runnable interface for creating a Thread?
The Thread can be created by using two ways.

By extending the Thread class
By implementing the Runnable interface
However, the primary differences between both the ways are given below:

By extending the Thread class, we cannot extend any other class, as Java does not allow multiple inheritances while implementing the Runnable interface; we can also extend other base class (if required).
By extending the Thread class, each of thread creates the unique object and associates with it while implementing the Runnable interface; multiple threads share the same object
Thread class provides various inbuilt methods such as getPriority(), isAlive() and more while the Runnable interface provides a single method, i.e., run().

12) What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. The join() method is overloaded in Thread class in the following ways.

public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
.
13) Describe the purpose and working of the sleep() method.
The sleep() method in Java is used to block a thread for a particular time, which means it pause the execution of a thread for a specific time. There are the following two methods to achieve the same:

Syntax:

public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos) throws InterruptedException
Working of sleep() Method

When we call the sleep() method, it pauses the execution of the current thread for the given time and gives priority to another thread (if available). Moreover, when the waiting time completed then again previous thread changes its state from waiting to runnable and comes in running state, and the whole process works so on until the execution does not complete.

14) What is the difference between wait() and sleep() method?
wait()
sleep()
The wait() method is defined in Object class.
The sleep() method is defined in Thread class.
The wait() method releases the lock.
The sleep() method does not release the lock.

15) Is it possible to start a thread twice?
No, we cannot restart the thread, once a thread started and executed, it goes to the Dead state. Therefore, if we try to start a thread twice, it will give a RuntimeException “java.lang.IllegalThreadStateException”. Consider the following example.

public class Multithread1 extends Thread
{
public void run()
{
try {
System.out.println(“thread is executing now……..”);
} catch(Exception e) {
}
}
public static void main (String[] args) {
Multithread1 m1= new Multithread1();
m1.start();
m1.start();
}
}
Output

thread is executing now……..
Exception in thread “main” java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at Multithread1.main(Multithread1.java:13)
.
16) Can we call the run() method instead of start()?
Yes, calling run() method directly is valid, but it will not work as a thread instead it will work as a normal object. There will not be context-switching between the threads. When we call the start() method, it internally calls the run() method that creates a new stack for a thread while directly calling the run() will not create a new stack.

.
17) What about the daemon threads?
The daemon threads are the low priority threads that provide the background support and services to the user threads. Daemon thread gets automatically terminated by the JVM if the program remains with the daemon thread only, and all other user threads are ended/died. There are two methods for daemon thread available in the Thread class:

public void setDaemon(boolean status): It used to mark the thread daemon thread or a user thread.
public boolean isDaemon(): It checks the thread is daemon or not.
.
18) Can we make the user thread as daemon thread if the thread is started?
No, if we do such, it will throw IllegalThreadStateException. Therefore, we can only create a daemon thread before starting the thread.

class Testdaemon1 extends Thread{
public void run(){
System.out.println(“Running thread is daemon…”);
}
public static void main (String[] args) {
Testdaemon1 td= new Testdaemon1();
td.start();
setDaemon(true);// It will throw the exception: td.
}
}
Output

Running thread is daemon…
Exception in thread “main” java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1359)
at Testdaemon1.main(Testdaemon1.java:8)
.
19) What is shutdown hook?
The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can use it to perform clean up the resource or save the state when JVM shuts down normally or abruptly. We can add shutdown hook by using the following method:

public void addShutdownHook(Thread hook){}
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
Some important points about shutdown hooks are :

Shutdown hooks initialized but can only be started when JVM shutdown occurred.
Shutdown hooks are more reliable than the finalizer() because there are very fewer chances that shutdown hooks not run.
The shutdown hook can be stopped by calling the halt(int) method of Runtime class.
.
20) When should we interrupt a thread?
We should interrupt a thread when we want to break out the sleep or wait state of a thread. We can interrupt a thread by calling the interrupt() throwing the InterruptedException.

.
21) What is synchronization?
Synchronization is the capability to control the access of multiple threads to any shared resource. It is used:

To prevent thread interference.
To prevent consistency problem.
When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence to remove this issue, Java uses the process of synchronization which allows only one thread to be executed at a time. Synchronization can be achieved in three ways:

by the synchronized method
by synchronized block
by static synchronization
Syntax for synchronized block

synchronized(object reference expression)
{
//code block
}

22)Can Java object be locked down for exclusive use by a given thread?
Yes, we 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.

.
23) What is the purpose of the Synchronized block?
The Synchronized block can be used to perform synchronization on any specific resource of the method. Only one thread at a time can execute on a particular resource, and all other threads which attempt to enter the synchronized block are blocked.

Synchronized block is used to lock an object for any shared resource.
The scope of the synchronized block is limited to the block on which, it is applied. Its scope is smaller than a method.
.

24) What is static synchronization?
If we declare any static method as synchronized, the lock will be on the class not on the object. If we use the synchronized keyword before a method so it will lock the object (one thread can access an object at a time) but if we use static synchronized so it will lock a class (one thread can access a class at a time).

.
25) What is the difference between notify() and notifyAll() method?
The notify() method is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

26) What is the deadlock situation in programming?
Deadlock is a situation in which every thread is waiting for a resource which is held by some other waiting thread. In this situation, neither of the thread executes nor it gets the chance to be executed. Instead, there exists a universal waiting state among all the threads. Deadlock is a very complicated situation that can break our code at runtime.

.
27) How to detect a deadlock condition? How can it be avoided?
We can detect the deadlock condition by running the code on CMD and collecting the Thread Dump, and if any deadlock is present in the code, then a message will appear on prompt (CMD).

There are the following ways to avoid the deadlock condition in Java:

Avoid Nested Lock: Nested lock is the common reason for deadlock. Deadlock occurs when we provide locks to various threads, so we should give one lock to only one thread at particular time.
Avoid Unnecessary Locks: We must avoid the locks which are not required.
Using Thread Join: Thread join helps to wait for a thread until another thread does not finish its execution. Therefore, we can avoid deadlock by maximizing the use of join() method.
28) What is Thread Scheduler in Java?
In Java, when we create the threads, they are supervised with the help of a Thread Scheduler that is the part of JVM. Thread scheduler is only responsible for deciding which thread should be executed. Thread scheduler uses two mechanisms for scheduling the threads: Preemptive and Time Slicing.

Java thread scheduler also works for deciding the following for a thread:

It selects the priority of the thread.
It determines the waiting time for a thread
It checks the Nature of thread
29) Does each thread have its stack in multithreaded programming?
Yes, in multithreaded programming every thread maintains its own or separate stack area in memory due to which every thread is independent of each other.

30) How can we achieved thread safety?
When a method or class object is used by multiple threads at a time without any race condition, then the class is thread-safe. Thread safety is used to make a program safe to use in multithreaded programming. It can be achieved by the following ways:

Using Synchronization
Using Volatile keyword
Using Lock Based Mechanism
Using Atomic Wrapper Classes
31) What is race-condition?
A race condition is a problem which occurs in the multithreaded programming when multiple threads try to execute simultaneously by accessing a shared resource at the same time. The proper use of synchronization can avoid the race condition.

32) What is the volatile keyword in Java?
Volatile keyword is used in multithreaded programming to achieve the thread safety, as a change in one volatile variable is visible to all other threads so one variable can be used by one thread at a time.

33) What do you understand by thread pool?
Java Thread pool represents a group of worker threads, which are waiting for the task to be allocated.
Threads in the thread pool are supervised by the service provider which pulls one thread from the pool and assign a job to it.
After completion of the given task, thread again came to the thread pool.
The size of the thread pool depends on the total number of threads kept at reserve for execution.
The advantages of the thread pool are :

Performance can be enhanced.
Better system stability can occur.
34) What is the difference between user-level and kernel-level threads?
User-level threads are managed by the application, and the operating system is unaware of their existence. On the other hand, Kernel-level threads are managed by the operating system kernel, providing better support for multitasking and parallel execution.

35) Explain the concept of race conditions in multithreading and how they can be mitigated.
Race conditions occur when the outcome of a program depends on the timing or interleaving of multiple threads accessing shared resources. They can be mitigated using synchronization mechanisms like locks, atomic variables, or by using immutable data structures.

36) What is the significance of the volatile keyword in Java multithreading?
The volatile keyword ensures that the value of a variable is always read from and written to main memory, rather than from a thread’s cache. It guarantees visibility of changes made by one thread to all other threads, preventing caching-related inconsistencies.

37) How does synchronization impact performance in multithreaded programs?
Synchronization can impact performance due to the overhead of acquiring and releasing locks. Excessive synchronization can lead to contention and reduced parallelism. It is important to balance synchronization to ensure thread safety without sacrificing performance.

38) What is the purpose of the Atomic classes?
The Atomic classes provide atomic operations on variables without requiring explicit synchronization. They are used to perform compound actions like incrementing a counter or updating a shared variable in a thread-safe manner.

39) Explain the concept of thread-local variables and their usage.
Thread-local variables are variables that have a separate copy for each thread. They are typically used to maintain thread-specific data without the need for synchronization. ThreadLocal class in Java provides support for creating thread-local variables.

40) Can we implement mutual exclusion without using synchronized blocks or methods?
Yes, mutual exclusion can be implemented using other synchronization mechanisms like ReentrantLock or Semaphore by using the java.util.concurrent package. These classes provide more flexibility and features compared to synchronized blocks.

41) Discuss the benefits and limitations of using locks in multithreaded programming.
Locks provide explicit control over synchronization and can handle more complex scenarios than intrinsic locks (synchronized blocks). However, they require careful management to avoid issues like deadlock and can introduce additional overhead compared to synchronized blocks.

42) What is the Java Memory Model, and how does it relate to multithreading?
The Java Memory Model defines how threads interact through memory. It ensures that changes made by one thread to shared variables are visible to other threads according to specific rules. Understanding the Java Memory Model is crucial for writing correct and efficient multithreaded programs.

43) How does Java handle thread priorities, and what are their implications?
Java provides thread priorities to influence the scheduling order of threads by the thread scheduler. Higher priority threads are scheduled with preference, but priority-based thread scheduling behavior can vary across different platforms and JVM implementations.

44) What is a daemon thread, and how does it differ from user threads?
A daemon thread is a low-priority thread that runs in the background, providing services to user threads. Unlike user threads, daemon threads do not prevent the JVM from exiting when all user threads have finished executing.

45) Discuss the advantages and disadvantages of using wait() and notify() methods for inter-thread communication.
Advantages: The wait() and notify() methods provide a simple mechanism for inter-thread communication, allowing threads to efficiently wait for specific conditions. It can be used to implement producer-consumer patterns and other synchronization scenarios.

Disadvantages: They require proper synchronization using synchronized blocks, and incorrect usage can lead to issues like missed signals or deadlock. Additionally, notify() wakes up only one waiting thread, which may not be desirable in some situations.

46) Explain the concept of thread safety and why it is important in concurrent programming.
Thread safety ensures that shared resources are accessed in a manner that avoids race conditions and maintains data consistency. It is crucial in concurrent programming to prevent unpredictable behavior and ensure the correctness of multithreaded programs.

47) What are the challenges associated with debugging multithreaded applications?
Multithreaded applications introduce non-deterministic behavior, making it difficult to reproduce and debug issues. Challenges include race conditions, deadlocks, and thread interleaving that require careful analysis and debugging techniques like thread dumps and synchronization debugging tools.

48) Explain the differences between optimistic and pessimistic locking?
Optimistic locking assumes that conflicts between threads are rare and allows multiple threads to access shared resources concurrently. On the other hand, pessimistic locking, assumes conflicts are common and restricts access to shared resources, typically using locks to enforce mutual exclusion.

49) How does Java support parallelism and concurrency in modern processors with multiple cores?
Java provides support for parallelism and concurrency through features like the Executor framework, ForkJoinPool, and java.util.concurrent package, allowing developers to leverage multiple cores for efficient execution of concurrent tasks.

50) What is the purpose of the Executor framework in Java, and how does it simplify multithreaded programming?
The Executor framework provides a higher-level abstraction for managing thread execution and scheduling tasks. It decouples task submission from execution, simplifies thread management, and allows for easy configuration of thread pools and task execution policies.

Concurrency Interview Questions
51) What are the main components of concurrency API?
Concurrency API can be developed using the class and interfaces of java.util.Concurrent package. There are the following classes and interfaces in java.util.Concurrent package.

Executor
FarkJoinPool
ExecutorService
ScheduledExecutorService
Future
TimeUnit(Enum)
CountDownLatch
CyclicBarrier
Semaphore
ThreadFactory
BlockingQueue
DelayQueue
Locks
Phaser
52) What is the Executor interface in Concurrency API in Java?
The Executor interface belong to the package java.util.concurrent. It is an interface used to execute the new task. The execute() method of the Executor interface is used to execute specified command. The syntax of the execute() method is given below.

void execute(Runnable command)
Consider the following example:

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
Executor e = Executors.newCachedThreadPool();
e.execute(new Thread());
ThreadPoolExecutor pool = (ThreadPoolExecutor)e;
pool.shutdown();
}

static class Thread implements Runnable {
public void run() {
try {
Long duration = (long) (Math.random() * 5);
System.out.println(“Running Thread!”);
TimeUnit.SECONDS.sleep(duration);
System.out.println(“Thread Completed”);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
Output

Running Thread!
Thread Completed
53) What is BlockingQueue?
The java.util.concurrent.BlockingQueue is the subinterface of Queue interface. It supports the operations such as waiting for the space availability before inserting a new value or waiting for the queue to become non-empty before retrieving an element from it. Consider the following example.

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class TestThread {

public static void main(final String[] arguments) throws InterruptedException {
BlockingQueue queue = new ArrayBlockingQueue(10);

  Insert i = new Insert(queue);  
  Retrieve r = new Retrieve(queue);  

  new Thread(i).start();  
  new Thread(r).start();  

  Thread.sleep(2000);  

}

static class Insert implements Runnable {
private BlockingQueue queue;

  public Insert(BlockingQueue queue) {  
     this.queue = queue;  
  }  

  @Override  
  public void run() {  
     Random random = new Random();  

     try {  
        int result = random.nextInt(200);  
        Thread.sleep(1000);  
        queue.put(result);  
        System.out.println("Added: " + result);  

        result = random.nextInt(10);  
        Thread.sleep(1000);  
        queue.put(result);  
        System.out.println("Added: " + result);  

        result = random.nextInt(50);  
        Thread.sleep(1000);  
        queue.put(result);  
        System.out.println("Added: " + result);  
     } catch (InterruptedException e) {  
        e.printStackTrace();  
     }  
  }      

}

static class Retrieve implements Runnable {
private BlockingQueue queue;

  public Retrieve(BlockingQueue queue) {  
     this.queue = queue;  
  }  

  @Override  
  public void run() {  

     try {  
        System.out.println("Removed: " + queue.take());  
        System.out.println("Removed: " + queue.take());  
        System.out.println("Removed: " + queue.take());  
     } catch (InterruptedException e) {  
        e.printStackTrace();  
     }  
  }  

}
}
Output

Added: 96
Removed: 96
Added: 8
Removed: 8
Added: 5
Removed: 5
54) How to implement producer-consumer problem by using BlockingQueue?
The producer-consumer problem can be solved by using BlockingQueue in the following way.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerProblem {
public static void main(String args[]){
//Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();

 //Creating Producer and Consumer Thread  
 Thread prod = new Thread(new Producer(sharedQueue));  
 Thread cons = new Thread(new Consumer(sharedQueue));  

 //Starting producer and Consumer thread  
 prod.start();  
 cons.start();  
}  

}

//Producer Class in Java
class Producer implements Runnable {

private final BlockingQueue sharedQueue;  

public Producer(BlockingQueue sharedQueue) {  
    this.sharedQueue = sharedQueue;  
}  

@Override  
public void run() {  
    for(int i=0; i<10; i++){  
        try {  
            System.out.println("Produced: " + i);  
            sharedQueue.put(i);  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);  
        }  
    }  
}  

}

//Consumer Class in Java
class Consumer implements Runnable{

private final BlockingQueue sharedQueue;  

public Consumer (BlockingQueue sharedQueue) {  
    this.sharedQueue = sharedQueue;  
}  

@Override  
public void run() {  
    while(true){  
        try {  
            System.out.println("Consumed: "+ sharedQueue.take());  
        } catch (InterruptedException ex) {  
            Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);  
        }  
    }  
}  

}
Output

Produced: 0
Produced: 1
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Produced: 6
Produced: 7
Produced: 8
Produced: 9
Consumed: 0
Consumed: 1
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Consumed: 7
Consumed: 8
Consumed: 9
55) What is the difference between Java Callable interface and Runnable interface?
The Callable and Runnable interface both are used by the classes which wanted to execute with multiple threads. However, there are the following key differences between the both:

A Callable interface can return a result, whereas the Runnable interface cannot return any result.
A Callable interface can throw a checked exception, whereas the Runnable interface cannot throw checked exception.
A Callable interface cannot be used prior Java 5 version whereas the Runnable interface can be used.
56) What is the Atomic action in Concurrency in Java?
The Atomic action is the operation which can be performed in a single unit of a task without any interference of the other operations.
The Atomic action cannot be stopped in between the task. Once started it fill stop after the completion of the task only.
An increment operation such as a++ does not allow an atomic action.
All reads and writes operation for the primitive variable (except long and double) are the atomic operation.
All reads and writes operation for the volatile variable (including long and double) are the atomic operation.
The Atomic methods are available in java.util.Concurrent package.
57) What is Lock interface in Concurrency API in Java?
The java.util.concurrent.locks.Lock interface is used as the synchronization mechanism. It works similar to the synchronized block. There are a few differences between the lock and synchronized block that are given below.

Lock interface provides the guarantee of sequence in which the waiting thread will be given the access, whereas the synchronized block does not guarantee it.
Lock interface provides the option of timeout if the lock is not granted whereas the synchronized block does not provide that.
The methods of Lock interface, i.e., lock() and unlock() can be called in different methods whereas single synchronized block must be fully contained in a single method.
58) Explain the ExecutorService Interface.
The ExecutorService Interface is the subinterface of Executor interface and adds the features to manage the lifecycle. Consider the following example.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
ExecutorService e = Executors.newSingleThreadExecutor();

  try {  
     e.submit(new Thread());  
     System.out.println("Shutdown executor");  
     e.shutdown();  
     e.awaitTermination(5, TimeUnit.SECONDS);  
  } catch (InterruptedException ex) {  
     System.err.println("tasks interrupted");  
  } finally {  

     if (!e.isTerminated()) {  
        System.err.println("cancel non-finished tasks");  
     }  
     e.shutdownNow();  
     System.out.println("shutdown finished");  
  }  

}

static class Task implements Runnable {

  public void run() {  

     try {  
        Long duration = (long) (Math.random() * 20);  
        System.out.println("Running Task!");  
        TimeUnit.SECONDS.sleep(duration);  
     } catch (InterruptedException ex) {  
        ex.printStackTrace();  
     }  
  }  

}
}
Output

Shutdown executor
shutdown finished
59) What are the differences between Synchronous programming and Asynchronous programming regarding a thread?
Synchronous Programming: In Synchronous programming model, a thread is assigned to complete a task and hence thread started working on it, and it is only available for other tasks once it will end the assigned task.

Asynchronous Programming: In Asynchronous programming, one job can be completed by multiple threads and hence it provides maximum usability of the various threads.

60) What do you understand by Callable and Future in Java?
Java Callable Interface: In Java 5, Callable interface defined in java.util.concurrent package. It is similar to the Runnable interface. But it can return a result, and it can throw an Exception. It also provides a run() method for execution of a thread. Java Callable can return any object as it uses Generic.

Syntax:

public interface Callable
Java Future interface: Java Future interface gives the result of a concurrent process. The Callable interface returns the object of java.util.concurrent.Future.

Java Future interface provides following methods for implementation.

cancel(boolean mayInterruptIfRunning): It is used to cancel the execution of the assigned task.
get(): It waits for the time if execution not completed and then retrieved the result.
isCancelled(): It returns the Boolean value as it returns true if the task was cancelled before the completion.
isDone(): It returns true if the job is completed successfully else returns false.
61) What is the difference between ScheduledExecutorService and ExecutorService interface?
ExecutorServcie and ScheduledExecutorService both are the interfaces of java.util.Concurrent package but scheduledExecutorService provides some additional methods to execute the Runnable and Callable tasks with the delay or every fixed time period.

62) Define FutureTask class in Java?
Java FutureTask class provides a base implementation of the Future interface. The result can only be obtained if the execution of one task is completed, and if the computation is not achieved then get method will be blocked. If the execution is completed, then it cannot be re-started and cannot be cancelled.

Syntax

public class FutureTask extends Object implements RunnableFuture
63) What is a Semaphore?
A Semaphore is a synchronization primitive that restricts the number of threads that can access a shared resource concurrently. It maintains a set of permits that control access to the resource, allowing a fixed number of threads to acquire permits and execute code that accesses the shared resource.

64) Explain the concept of a CountdownLatch.
CountdownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. It is initialized with a count, and each thread decrements the count when it completes its operation. Threads waiting on the latch are released when the count reaches zero.

65) What is a CyclicBarrier and how is it used?
A CyclicBarrier is a synchronization aid that allows a group of threads to wait at a predefined barrier until all threads reach the barrier before proceeding. Once all threads have reached the barrier, they are released simultaneously. CyclicBarrier can be reset to its initial state after all threads have crossed the barrier.

66) Discuss the purpose of the Phaser class.
Phaser is a synchronization barrier that allows multiple threads to synchronize their execution at predefined phases. It provides more flexible synchronization than CountDownLatch and CyclicBarrier, allowing threads to dynamically register and deregister at different phases. Phaser can be used for implementing multi-phase algorithms.

67) What is the purpose of the Exchanger class?
The Exchanger class provides a synchronization point at which two threads can exchange objects. Each thread calls the exchange() method, providing an object to exchange, and waits until the other thread also calls exchange(). Once both threads have called exchange(), they swap their objects and continue execution.

68) Explain the concept of thread confinement.
Thread confinement is a concurrency control technique where a particular data is accessible only by a single thread at a time. It ensures that the data remains consistent and avoids race conditions by preventing concurrent access from multiple threads. Thread confinement can be achieved by encapsulating the data within a thread or using synchronization mechanisms.

69) What is the purpose of the ReadWriteLock interface?
The ReadWriteLock interface provides a mechanism for controlling access to shared resources in a multi-threaded environment. Unlike traditional locks, ReadWriteLock allows multiple threads to read the resource concurrently while providing exclusive access for writing. It can improve performance in scenarios where reads are more frequent than writes.

70) Discuss the concept of thread-safe collections.
Thread-safe collections are data structures provided by the java.util.concurrent package that can be safely accessed and modified by multiple threads concurrently. These collections, such as ConcurrentHashMap and CopyOnWriteArrayList, handle synchronization internally to ensure thread safety without requiring external synchronization by the user.

71) What is the purpose of the ForkJoinPool class?
ForkJoinPool is a special-purpose ExecutorService implementation designed for parallelizing recursive divide-and-conquer algorithms. It manages a pool of worker threads that execute tasks using a work-stealing algorithm, where idle threads steal tasks from other threads’ queues to maximize CPU utilization and minimize contention.

72) Explain the concept of parallel streams.
Parallel streams are a feature introduced in Java 8 to leverage multi-core processors for parallel execution of stream operations. They enable automatic parallelization of operations like map, filter, and reduce on collections, distributing the workload across multiple threads for improved performance on multi-core systems.

73) What is the purpose of the CompletableFuture class?
CompletableFuture is a class introduced in Java 8 to represent a future result of an asynchronous computation. It provides a powerful API for composing asynchronous operations, handling exceptions, and chaining dependent computations. CompletableFuture supports both synchronous and asynchronous execution, making it versatile for building complex asynchronous workflows.

74) Discuss the concept of non-blocking algorithms.
Non-blocking algorithms are concurrency control techniques that ensure progress even in the presence of contention or thread failures without requiring locks or blocking synchronization primitives. They use atomic operations and compare-and-swap (CAS) instructions to perform operations on shared data without blocking threads, leading to better scalability and responsiveness.

75) What is the purpose of the Phaser class?
Phaser is a synchronization barrier introduced in Java 7 that allows synchronization of threads across multiple phases. It is similar to CountDownLatch and CyclicBarrier but provides more flexibility by allowing dynamic registration and deregistration of parties (threads) at different phases. Phaser supports both one-shot and cyclic synchronization scenarios.

76) Discuss the concept of the ThreadLocal class.
ThreadLocal is a class provided in Java to create thread-local variables, where each thread has its own independent copy of the variable. ThreadLocal variables are typically used to store thread-specific data without the need for synchronization, improving performance and reducing contention in multithreaded applications.

77) What is the purpose of the LockSupport class?
LockSupport is a utility class provided in Java for low-level thread synchronization. It allows threads to block and unblock based on the availability of permits, similar to wait() and notify() methods, but with more flexibility and control. LockSupport can be used to implement custom synchronization primitives and coordination mechanisms between threads.

78) How to define the stack size explicitly for a Thread?
The Thread class provides a constructor through which we can determine the stack size explicitly for the new thread.

new Thread(ThreadGroup group, Runnable target, String name, long stackSize);
The effect of the stackSize parameter, if any, is highly platform dependent. In some platforms, a higher value of stack size may allow a deeper recursion depth before throwing StackOverflowError, and in other platforms, it may not have any effect at all.

79) Can we override Thread.start() method?
Yes, we can override the Thread.start() method, but note that overridden method will be executed just like a normal method call executed by the main thread only. It will not seed a new Thread similar to the default start() method. Consider the following example.

class ChildThread extends Thread {
public void start() {
System.out.println(“Overriding start() method in ChildThread”);
}
public void run(){
System.out.println(“ChildThread run() method”);
}
}
The above code snippet creates a new ChildThread instance and call its start() method. It does not start a new thread and run() method is not executed.

ChildThread childThread = new ChildThread();
childThread.start();
Output:

Overriding start() method in ChildThread
To initialize a new Thread, we must call the super.start() method from the child thread; only then the run() method will be executed.

public void start() {
super.start(); //Calling Thread.start()
System.out.println(“Overriding start() method in ChildThread”);
}
Output:

Overriding start() method in ChildThread
ChildThread run() method
80) What is thread priority? What is the default thread priority?
In Java, JVM assigns a number between 1 to 10 to each thread that is known as thread priority. Priority is used by the thread scheduler at the time of thread execution. While allocating the processor to the thread, the thread scheduler gives the first chance to the thread with the highest priority.

Note that the default priority for any thread is inherited from the parent thread. The default priority for the main thread is 5, so all the child threads will have the default priority of 5.

The Thread class defines three constants to represent the min, max, and default priority of any thread.

Thread.MIN_PRIORITY = 1;

Thread.NORM_PRIORITY = 5;

Thread.MAX_PRIORITY = 10;

81) What is daemon thread?
Daemon Threads are the low-priority threads. It executes in the background to provide support for the non-daemon threads (a thread that executes the main logic of the project is called a non-daemon or user thread). Daemon Threads in Java are also known as Service Provider Threads.

Properties of Daemon Threads:

The life cycle of daemon threads depends on user threads. It provides services to user threads for background supporting tasks.
They cannot prevent the JVM from exiting when all the user threads finish their execution.
When all the user threads terminate, JVM terminates Daemon threads automatically.
It is a thread with the lowest priority possible.
JVM would not be concerned about whether the Daemon thread is active or not.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *