fbpx

Top 100 Multithreading Interview Questions and Answers

Top 100 Multithreading Interview Questions and Answers

Contents show

1. What is multithreading?

Multithreading is a programming concept where a process is divided into multiple threads of execution that can run concurrently, allowing tasks to be performed simultaneously.

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

2. How does multithreading differ from multiprocessing?

Multithreading involves multiple threads within the same process sharing the same memory space, while multiprocessing involves separate processes with their own memory spaces.


3. Explain the difference between process and thread.

A process is an instance of a program in execution, with its own memory space. A thread is a unit of execution within a process and shares the same memory space with other threads.


4. What is the purpose of the synchronized keyword in Java?

The synchronized keyword is used to create a synchronized block of code or method, allowing only one thread to access it at a time, ensuring thread safety.

Example:

public synchronized void synchronizedMethod() {
    // Code inside this method is thread-safe
}

5. What is a deadlock in multithreading?

A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock, resulting in a standstill.


6. How can you prevent a deadlock in multithreading?

Avoid circular dependencies in lock acquisition, use timeout when acquiring locks, and ensure a consistent order of acquiring locks.


7. Explain the concept of thread pooling.

Thread pooling involves creating a group of threads that can be reused for executing tasks, improving performance and resource utilization.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Task());
executor.shutdown();

8. What is the purpose of the volatile keyword in Java?

The volatile keyword ensures that a variable is always read from main memory and not from thread caches, making it suitable for shared variables in multithreaded environments.

Example:

public class VolatileExample {
    private volatile boolean flag = false;

    public void toggleFlag() {
        flag = !flag;
    }
}

9. What is a race condition in multithreading?

A race condition occurs when two or more threads attempt to modify a shared resource simultaneously, potentially leading to unpredictable behavior.


10. Explain the producer-consumer problem in multithreading.

The producer-consumer problem involves two processes, one producing data and the other consuming it. Synchronization mechanisms are used to prevent issues like data overflow or deadlock.


11. What are the advantages of multithreading?

  • Improved performance by utilizing multiple CPU cores.
  • Efficient resource utilization.
  • Enhanced responsiveness in user interfaces.
  • Simplifies complex tasks by breaking them into smaller threads.

12. Explain the join() method in Java.

The join() method is used to wait for a thread to complete its execution before moving forward in the program.

Example:

Thread thread = new Thread(() -> {
    // Task
});
thread.start();
try {
    thread.join(); // Wait for thread to finish
} catch (InterruptedException e) {
    e.printStackTrace();
}

13. What is a thread-safe class?

A thread-safe class is designed to be safely used in a multithreaded environment without causing race conditions or other synchronization issues.


14. How do you implement a thread-safe singleton in Java?

You can use the Bill Pugh Singleton design pattern, which ensures lazy initialization and thread safety.

Example:

public class Singleton {
    private Singleton() {}

    private static class SingletonHelper {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHelper.INSTANCE;
    }
}

15. What is the purpose of the ReentrantLock class in Java?

The ReentrantLock class provides a way to create exclusive locks that allow a thread to enter a critical section.

Example:

ReentrantLock lock = new ReentrantLock();

lock.lock(); // Acquire lock
try {
    // Critical section
} finally {
    lock.unlock(); // Release lock
}

16. Explain the concept of thread priority.

Thread priority is a value assigned to a thread that influences its scheduling by the thread scheduler. Higher priority threads are more likely to be scheduled first.

Example:

Thread thread1 = new Thread(() -> {
    // Task
});
thread1.setPriority(Thread.MAX_PRIORITY); // Set highest priority

17. What is the purpose of the Callable interface in Java?

The Callable interface is similar to Runnable, but it can return a result or throw an exception.

Example:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
    return 42;
});
int result = future.get();

18. Explain the concept of thread-local variables.

Thread-local variables are variables that have their own unique copy for each thread. They are useful for storing data that is specific to a particular thread.

Example:

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

// In a thread:
threadLocal.set(42);
int value = threadLocal.get(); // Returns 42

19. How do you handle exceptions in multithreading?

You can catch exceptions within the thread’s run() method and handle them appropriately.

Example:

Thread thread = new Thread(() -> {
    try {
        // Risky operation
    } catch (Exception e) {
        // Handle exception
    }
});

20. Explain the wait() and notify() methods in Java.

wait() is used to make a thread pause execution until it’s notified. notify() wakes up one waiting thread.

Example:

Object monitor = new Object();

// In one thread:
synchronized (monitor) {
    monitor.wait();
}

// In another thread:
synchronized (monitor) {
    monitor.notify();
}

21. What is the purpose of the BlockingQueue interface in Java?

The BlockingQueue interface provides a thread-safe queue that supports operations like put (to add) and take (to remove) elements.

Example:

BlockingQueue<String> queue = new LinkedBlockingQueue<>();

// Producer
queue.put("item");

// Consumer
String item = queue.take();

22. Explain the concept of thread starvation.

Thread starvation occurs when a thread is unable to gain regular access to shared resources, causing it to be constantly delayed or blocked.


23. How can you interrupt a thread in Java?

You can use the interrupt() method to signal a thread to stop. The thread must periodically check for interruptions using isInterrupted().

Example:

Thread thread = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        // Task
    }
});
thread.start();
thread.interrupt(); // Signal thread to stop

24. What is the purpose of the ThreadLocalRandom class in Java?

ThreadLocalRandom provides a fast, thread-safe way to generate random numbers.

Example:

int randomNum = ThreadLocalRandom.current().nextInt(0, 100);

25. Explain the concept of thread group.

A thread group is a way to group multiple threads together for easier management. It can be used to perform operations on multiple threads simultaneously.

Example:

ThreadGroup group = new ThreadGroup("MyThreadGroup");

Thread thread1 = new Thread(group, () -> {
    // Task
});

26. What is a thread dump and how can you generate it?

A thread dump is a snapshot of the state of all threads in a Java Virtual Machine (JVM). You can generate it using tools like jstack.

Example:

jstack <pid>

27. Explain the concept of thread pools in Java.

A thread pool is a collection of threads that can be reused for executing tasks, which improves performance and resource management.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Task());
executor.shutdown();

28. What is the purpose of the ReadWriteLock interface in Java?

The ReadWriteLock interface provides a way to have multiple readers and a single writer for a resource. It improves performance when there are more reads than writes.

Example:

ReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock(); // Acquire read lock
// Perform read operation
lock.readLock().unlock(); // Release read lock

lock.writeLock().lock(); // Acquire write lock
// Perform write operation
lock.writeLock().unlock(); // Release write lock

29. How do you create a thread in Java?

You can create a thread by extending the Thread class or implementing the Runnable interface and passing it to a Thread object.

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
}

30. Explain the purpose of the yield() method in Java.

The yield() method is used to hint to the scheduler that the current thread is willing to release the CPU for other tasks.

Example:

Thread.yield(); // Suggest to scheduler to switch to another thread

31. What is the purpose of the CountDownLatch class in Java?

The CountDownLatch class allows one or more threads to wait for a set of operations to complete before proceeding.

Example:

CountDownLatch latch = new CountDownLatch(3);

// In multiple threads:
latch.countDown();

// In another thread:
latch.await(); // Waits until count reaches zero

32. Explain the concept of a daemon thread.

A daemon thread is a background thread that does not prevent the JVM from exiting if it’s the only thread running.

Example:

Thread daemonThread = new Thread(() -> {
    // Task
});
daemonThread.setDaemon(true);
daemonThread.start();

33. How do you handle thread synchronization in Java?

You can use synchronization blocks or methods, volatile keyword, locks, or atomic classes to achieve thread synchronization.

Example using synchronized block:

public void synchronizedMethod() {
    synchronized(this) {
        // Synchronized code
    }
}

34. What is the purpose of the CyclicBarrier class in Java?

The CyclicBarrier class is used to synchronize a group of threads at a certain point, where each thread waits for others to reach the same point.

Example:

CyclicBarrier barrier = new CyclicBarrier(3);

// In multiple threads:
barrier.await(); // Waits until all threads reach the barrier

35. Explain the concept of the Exchanger class in Java.

The Exchanger class provides a point at which threads can pair and swap elements within pairs.

Example:

Exchanger<String> exchanger = new Exchanger<>();

// In thread 1:
String data1 = exchanger.exchange("Data from thread 1");

// In thread 2:
String data2 = exchanger.exchange("Data from thread 2");

36. What is the purpose of the LockSupport class in Java?

The LockSupport class provides a way to block and unblock threads, allowing for more fine-grained control than wait() and notify().

Example:

Thread thread = new Thread(() -> {
    LockSupport.park(); // Block thread
    // Task
});
LockSupport.unpark(thread); // Unblock thread

37. Explain the concept of thread priority inversion.

Thread priority inversion occurs when a higher-priority thread is blocked waiting for a resource held by a lower-priority thread.


38. How do you implement the Runnable interface in Java?

You can implement the Runnable interface by providing an implementation for the run() method.

Example:

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable is running...");
    }
}

39. What is the purpose of the CompletableFuture class in Java?

CompletableFuture is used for asynchronous programming in Java, allowing you to chain multiple operations together.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApplyAsync(result -> result + " World");
String result = future.get();

40. Explain the concept of thread context switching.

Thread context switching is the process of saving the current state of a thread and restoring the state of another thread for execution. It involves overhead and affects performance.


41. What is the purpose of the Semaphore class in Java?

The Semaphore class is used to control access to a resource by limiting the number of threads that can access it simultaneously.

Example:

Semaphore semaphore = new Semaphore(3); // Allow 3 threads at a time

// In multiple threads:
semaphore.acquire(); // Acquire permit
// Perform task
semaphore.release(); // Release permit

42. Explain the concept of the ScheduledExecutorService in Java.

ScheduledExecutorService is a specialized ExecutorService that can schedule tasks to run after a certain delay or at regular intervals.

Example:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(() -> {
    // Task
}, 0, 1, TimeUnit.SECONDS); // Run every second

43. How do you handle concurrent modification in Java?

You can use an Iterator to avoid concurrent modification exceptions when iterating over collections.

Example:

List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    // Modify list
    iterator.remove(); // Safe removal
}

44. What is the purpose of the Phaser class in Java?

The Phaser class provides a synchronization point for a set of threads, allowing them to arrive and wait at a barrier.

Example:

Phaser phaser = new Phaser(3); // Expecting 3 parties

// In multiple threads:
phaser.arriveAndAwaitAdvance(); // Wait for others

45. Explain the concept of the StampedLock class in Java.

StampedLock is a read-write lock that allows for optimistic locking, potentially improving performance for read-heavy workloads.

Example:

StampedLock lock = new StampedLock();

long stamp = lock.tryOptimisticRead(); // Optimistic read
// Read data
if (!lock.validate(stamp)) {
    stamp = lock.readLock(); // Fallback to normal read lock
    try {
        // Read data
    } finally {
        lock.unlockRead(stamp);
    }
}

46. What is the purpose of the CompletableFuture class in Java?

CompletableFuture is used for asynchronous programming in Java, allowing you to chain multiple operations together.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApplyAsync(result -> result + " World");
String result = future.get();

47. How do you implement a thread-safe counter in Java?

You can use the AtomicInteger class to implement a thread-safe counter.

Example:

AtomicInteger counter = new AtomicInteger(0);

public void increment() {
    counter.incrementAndGet();
}

public int getCount() {
    return counter.get();
}

48. Explain the concept of the ThreadLocalRandom class in Java.

ThreadLocalRandom provides a fast, thread-safe way to generate random numbers.

Example:

int randomNum = ThreadLocalRandom.current().nextInt(0, 100);

49. What is the purpose of the LockSupport class in Java?

The LockSupport class provides a way to block and unblock threads, allowing for more fine-grained control than wait() and notify().

Example:

Thread thread = new Thread(() -> {
    LockSupport.park(); // Block thread
    // Task
});
LockSupport.unpark(thread); // Unblock thread

50. Explain the purpose of the yield() method in Java.

The yield() method is used to hint to the scheduler that the current thread is willing to release the CPU for other tasks.

Example:

Thread.yield(); // Suggest to scheduler to switch to another thread

51. What is the purpose of the Lock interface in Java?

The Lock interface provides a more flexible way to manage thread synchronization compared to synchronized blocks or methods.

Example:

Lock lock = new ReentrantLock();

lock.lock(); // Acquire lock
try {
    // Critical section
} finally {
    lock.unlock(); // Release lock
}

52. Explain the concept of the ForkJoinPool in Java.

ForkJoinPool is a special type of ExecutorService designed for tasks that can be broken down into smaller subtasks, commonly used in recursive algorithms.

Example:

ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(new RecursiveTask());

53. How do you implement a thread-safe queue in Java?

You can use classes like LinkedBlockingQueue or ConcurrentLinkedQueue to implement a thread-safe queue.

Example using LinkedBlockingQueue:

BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("item"); // Add item
String item = queue.take(); // Remove item

54. What is the purpose of the CompletableFuture class in Java?

CompletableFuture is used for asynchronous programming in Java, allowing you to chain multiple operations together.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApplyAsync(result -> result + " World");
String result = future.get();

55. Explain the concept of the Semaphore class in Java.

The Semaphore class is used to control access to a resource by limiting the number of threads that can access it simultaneously.

Example:

Semaphore semaphore = new Semaphore(3); // Allow 3 threads at a time

// In multiple threads:
semaphore.acquire(); // Acquire permit
// Perform task
semaphore.release(); // Release permit

56. What is the purpose of the CyclicBarrier class in Java?

The CyclicBarrier class is used to synchronize a group of threads at a certain point, where each thread waits for others to reach the same point.

Example:

CyclicBarrier barrier = new CyclicBarrier(3);

// In multiple threads:
barrier.await(); // Waits until all threads reach the barrier

57. Explain the concept of a deadlock in multithreading.

A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock, resulting in a standstill.


58. What is the purpose of the BlockingQueue interface in Java?

The BlockingQueue interface provides a thread-safe queue that supports operations like put (to add) and take (to remove) elements.

Example:

BlockingQueue<String> queue = new LinkedBlockingQueue<>();

// Producer
queue.put("item");

// Consumer
String item = queue.take();

59. Explain the concept of thread starvation.

Thread starvation occurs when a thread is unable to gain regular access to shared resources, causing it to be constantly delayed or blocked.


60. How do you implement a thread pool in Java?

You can use the ExecutorService framework to create and manage a thread pool.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Task());
executor.shutdown();

61. What is the purpose of the Lock interface in Java?

The Lock interface provides a more flexible way to manage thread synchronization compared to synchronized blocks or methods.

Example:

Lock lock = new ReentrantLock();

lock.lock(); // Acquire lock
try {
    // Critical section
} finally {
    lock.unlock(); // Release lock
}

62. Explain the concept of the ForkJoinPool in Java.

ForkJoinPool is a special type of ExecutorService designed for tasks that can be broken down into smaller subtasks, commonly used in recursive algorithms.

Example:

ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(new RecursiveTask());

63. How do you implement a thread-safe queue in Java?

You can use classes like LinkedBlockingQueue or ConcurrentLinkedQueue to implement a thread-safe queue.

Example using LinkedBlockingQueue:

BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("item"); // Add item
String item = queue.take(); // Remove item

64. What is the purpose of the CompletableFuture class in Java?

CompletableFuture is used for asynchronous programming in Java, allowing you to chain multiple operations together.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApplyAsync(result -> result + " World");
String result = future.get();

65. Explain the concept of the Semaphore class in Java.

The Semaphore class is used to control access to a resource by limiting the number of threads that can access it simultaneously.

Example:

Semaphore semaphore = new Semaphore(3); // Allow 3 threads at a time

// In multiple threads:
semaphore.acquire(); // Acquire permit
// Perform task
semaphore.release(); // Release permit

66. What is the purpose of the CyclicBarrier class in Java?

The CyclicBarrier class is used to synchronize a group of threads at a certain point, where each thread waits for others to reach the same point.

Example:

CyclicBarrier barrier = new CyclicBarrier(3);

// In multiple threads:
barrier.await(); // Waits until all threads reach the barrier

67. Explain the concept of a deadlock in multithreading.

A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a lock, resulting in a standstill.


68. What is the purpose of the BlockingQueue interface in Java?

The BlockingQueue interface provides a thread-safe queue that supports operations like put (to add) and take (to remove) elements.

Example:

BlockingQueue<String> queue = new LinkedBlockingQueue<>();

// Producer
queue.put("item");

// Consumer
String item = queue.take();

69. Explain the concept of thread starvation.

Thread starvation occurs when a thread is unable to gain regular access to shared resources, causing it to be constantly delayed or blocked.


70. How do you implement a thread pool in Java?

You can use the ExecutorService framework to create and manage a thread pool.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Task());
executor.shutdown();

71. What is the purpose of the Lock interface in Java?

The Lock interface provides a more flexible way to manage thread synchronization compared to synchronized blocks or methods.

Example:

Lock lock = new ReentrantLock();

lock.lock(); // Acquire lock
try {
    // Critical section
} finally {
    lock.unlock(); // Release lock
}

72. Explain the concept of the ForkJoinPool in Java.

ForkJoinPool is a special type of ExecutorService designed for tasks that can be broken down into smaller subtasks, commonly used in recursive algorithms.

Example:

ForkJoinPool forkJoinPool = a ForkJoinPool();
forkJoinPool.invoke(new RecursiveTask());

73. How do you implement a thread-safe counter in Java?

You can use the AtomicInteger class to implement a thread-safe counter.

Example:

AtomicInteger counter = new AtomicInteger(0);

public void increment() {
    counter.incrementAndGet();
}

public int getCount() {
    return counter.get();
}

74. Explain the concept of the ThreadLocalRandom class in Java.

ThreadLocalRandom provides a fast, thread-safe way to generate random numbers.

Example:

int randomNum = ThreadLocalRandom.current().nextInt(0, 100);

75. What is the purpose of the LockSupport class in Java?

The LockSupport class provides a way to block and unblock threads, allowing for more fine-grained control than wait() and notify().

Example:

Thread thread = new Thread(() -> {
    LockSupport.park(); // Block thread
    // Task
});
LockSupport.unpark(thread); // Unblock thread

76. Explain the concept of the StampedLock class in Java.

StampedLock is a read-write lock that allows for optimistic locking, potentially improving performance for read-heavy workloads.

Example:

StampedLock lock = new StampedLock();

long stamp = lock.tryOptimisticRead(); // Optimistic read
// Read data
if (!lock.validate(stamp)) {
    stamp = lock.readLock(); // Fallback to normal read lock
    try {
        // Read data
    } finally {
        lock.unlockRead(stamp);
    }
}

77. What is the purpose of the ThreadLocalRandom class in Java?

ThreadLocalRandom provides a fast, thread-safe way to generate random numbers.

Example:

int randomNum = ThreadLocalRandom.current().nextInt(0, 100);

78. How do you implement a thread-safe counter in Java?

You can use the AtomicInteger class to implement a thread-safe counter.

Example:

AtomicInteger counter = new AtomicInteger(0);

public void increment() {
    counter.incrementAndGet();
}

public int getCount() {
    return counter.get();
}

79. Explain the purpose of the yield() method in Java.

The yield() method is used to hint to the scheduler that the current thread is willing to release the CPU for other tasks.

Example:

Thread.yield(); // Suggest to scheduler to switch to another thread

80. What is the purpose of the LockSupport class in Java?

The LockSupport class provides a way to block and unblock threads, allowing for more fine-grained control than wait() and notify().

Example:

Thread thread = new Thread(() -> {
    LockSupport.park(); // Block thread
    // Task
});
LockSupport.unpark(thread); // Unblock thread

81. Explain the purpose of the CompletableFuture class in Java.

CompletableFuture is used for asynchronous programming in Java, allowing you to chain multiple operations together.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApplyAsync(result -> result + " World");
String result = future.get();

82. How do you implement a thread pool in Java?

You can use the ExecutorService framework to create and manage a thread pool.

Example:

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Task());
executor.shutdown();

83. Explain the concept of the Lock interface in Java.

The Lock interface provides a more flexible way to manage thread synchronization compared to synchronized blocks or methods.

Example:

Lock lock = new ReentrantLock();

lock.lock(); // Acquire lock
try {
    // Critical section
} finally {
    lock.unlock(); // Release lock
}

84. What is the purpose of the ForkJoinPool in Java?

ForkJoinPool is a special type of ExecutorService designed for tasks that can be broken down into smaller subtasks, commonly used in recursive algorithms.

Example:

ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(new RecursiveTask());

85. Explain the concept of a daemon thread.

A daemon thread is a background thread that does not prevent the JVM from exiting if it’s the only thread running.

Example:

Thread daemonThread = new Thread(() -> {
    // Task
});
daemonThread.setDaemon(true);
daemonThread.start();

86. How do you handle thread synchronization in Java?

You can use synchronization blocks or methods, volatile keyword, locks, or atomic classes to achieve thread synchronization.

Example using synchronized block:

public void synchronizedMethod() {
    synchronized(this) {
        // Synchronized code
    }
}

87. What is the purpose of the CyclicBarrier class in Java?

The CyclicBarrier class is used to synchronize a group of threads at a certain point, where each thread waits for others to reach the same point.

Example:

CyclicBarrier barrier = new CyclicBarrier(3);

// In multiple threads:
barrier.await(); // Waits until all threads reach the barrier

88. Explain the concept of the Exchanger class in Java.

The Exchanger class provides a point at which threads can pair and swap elements within pairs.

Example:

Exchanger<String> exchanger = new Exchanger<>();

// In thread 1:
String data1 = exchanger.exchange("Data from thread 1");

// In thread 2:
String data2 = exchanger.exchange("Data from thread 2");

89. What is the purpose of the LockSupport class in Java?

The LockSupport class provides a way to block and unblock threads, allowing for more fine-grained control than wait() and notify().

Example:

Thread thread = new Thread(() -> {
    LockSupport.park(); // Block thread
    // Task
});
LockSupport.unpark(thread); // Unblock thread

90. Explain the concept of thread priority inversion.

Thread priority inversion occurs when a higher-priority thread is blocked waiting for a resource held by a lower-priority thread.


91. What is the purpose of the ReadWriteLock interface in Java?

The ReadWriteLock interface provides a way to have multiple readers and a single writer for a resource. It improves performance when there are more reads than writes.

Example:

ReadWriteLock lock = new ReentrantReadWriteLock();
lock.readLock().lock(); // Acquire read lock
// Perform read operation
lock.readLock().unlock(); // Release read lock

lock.writeLock().lock(); // Acquire write lock
// Perform write operation
lock.writeLock().unlock(); // Release write lock

92. How do you implement a thread-safe list in Java?

You can use Collections.synchronizedList or use CopyOnWriteArrayList for thread-safe lists.

Example using CopyOnWriteArrayList:

List<String> list = new CopyOnWriteArrayList<>();
list.add("item"); // Add item
String item = list.get(0); // Get item

93. Explain the concept of thread context switching.

Thread context switching is the process of saving the current state of a thread, including its program counter and register values, and restoring the state of another thread.


94. What is the purpose of the BlockingDeque interface in Java?

The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations.

Example:

BlockingDeque<String> deque = new LinkedBlockingDeque<>();
deque.offerFirst("item"); // Add to front
String item = deque.pollFirst(); // Remove from front

95. Explain the concept of thread preemption.

Thread preemption occurs when a higher-priority thread temporarily stops a lower-priority thread to execute its own code.


96. What is the purpose of the TransferQueue interface in Java?

The TransferQueue interface extends BlockingQueue to support asynchronous transfer of elements between producer and consumer threads.

Example:

TransferQueue<String> queue = new LinkedTransferQueue<>();
queue.transfer("item"); // Transfer item to a waiting consumer

97. How do you implement a thread-safe map in Java?

You can use Collections.synchronizedMap or use ConcurrentHashMap for thread-safe maps.

Example using ConcurrentHashMap:

Map<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1); // Put entry
int value = map.get("key"); // Get value

98. Explain the concept of the ScheduledExecutorService in Java.

ScheduledExecutorService is a specialized ExecutorService that can schedule tasks to run after a certain delay or at regular intervals.

Example:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(() -> {
    // Task
}, 0, 1, TimeUnit.SECONDS); // Run every second

99. What is the purpose of the Phaser class in Java?

The Phaser class provides a synchronization point for a set of threads, allowing them to arrive and wait at a barrier.

Example:

Phaser phaser = new Phaser(3); // Expecting 3 parties

// In multiple threads:
phaser.arriveAndAwaitAdvance(); // Wait for others

100. Explain the concept of the ThreadMXBean in Java.

ThreadMXBean is a management interface for the thread system of the Java Virtual Machine, allowing for monitoring and control of threads.

Example (monitoring thread count):

ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
int threadCount = threadMXBean.getThreadCount();