Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Java Threads Interview Questions Answers

Uploaded by

Prasoon Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Java Threads Interview Questions Answers

Uploaded by

Prasoon Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Java Threads Interview Questions & Answers

1. What is a Thread in Java?

A thread is a lightweight sub-process, the smallest unit of processing. Java allows multiple threads

to run concurrently within a program, sharing resources but executing independently. Each thread is

created and controlled by the java.lang.Thread class.

2. What is the difference between Thread and Runnable?

Thread: A class in Java that represents a thread of execution.

Runnable: An interface in Java that is used to define the code that constitutes the thread's task.

Difference: You can either extend Thread (but then cannot extend any other class due to single

inheritance) or implement Runnable and pass it to a Thread object. Using Runnable is more flexible.

3. How do you create a thread in Java?

Two ways:

1. Extending Thread: You create a subclass of Thread and override the run() method.

2. Implementing Runnable: You implement the Runnable interface and pass the object to a Thread

object.

4. What are the different states of a Thread in Java?

New: Thread is created but not started.

Runnable: Thread is ready to run but waiting for CPU time.

Blocked: Thread is waiting for a monitor lock.

Waiting: Thread is waiting indefinitely for another thread to perform an action.

Timed Waiting: Thread is waiting for another thread for a specified waiting time.

Terminated: Thread has finished execution.

5. What is a daemon thread in Java?

Daemon threads run in the background and do not prevent the JVM from exiting once all user
threads finish execution. Examples include garbage collector threads. You can set a thread as

daemon using setDaemon(true).

6. What is thread synchronization and why is it needed?

Synchronization is used to control access to shared resources by multiple threads to avoid

inconsistent data. Without it, multiple threads could interfere with each other, causing issues like

race conditions.

7. What are the ways to synchronize threads in Java?

You can use:

- Synchronized methods: The entire method is locked.

- Synchronized blocks: Only a part of the code is synchronized.

- Static synchronization: Used when the synchronized method is static, locking the class object

instead of the instance.

8. What is the difference between synchronized block and synchronized method?

A synchronized method locks the entire method for a single thread, while a synchronized block locks

only a portion of the code within a method, allowing more flexibility and better performance.

9. What is a deadlock in Java? How can you prevent deadlock?

Deadlock occurs when two or more threads block each other by holding resources the other needs.

Prevention:

- Lock ordering: Always acquire locks in the same order.

- Timeout: Use tryLock() with time limits.

- Avoid holding multiple locks at the same time.

10. What is a volatile keyword in Java and how is it used in the context of threads?

volatile ensures that the value of a variable is always read from the main memory and not from the

thread's local cache. It guarantees visibility of changes across threads.


11. What is the difference between volatile and synchronized?

volatile ensures visibility of changes to variables across threads but does not guarantee atomicity,

while synchronized ensures both visibility and atomicity by locking the critical section.

12. What is ThreadLocal in Java?

ThreadLocal provides each thread with its own copy of a variable, ensuring that no two threads

share the same instance. It's useful when you need a variable per thread without synchronization.

13. What is the Java Memory Model (JMM)?

The Java Memory Model defines how threads interact through memory and governs the visibility of

changes to variables across threads. It ensures that memory writes by one thread are visible to

other threads under certain conditions, like synchronization or use of volatile.

14. What is the difference between wait(), notify(), and notifyAll()?

These are used for inter-thread communication in synchronization.

- wait(): Causes the current thread to wait until another thread calls notify() or notifyAll().

- notify(): Wakes up one waiting thread.

- notifyAll(): Wakes up all waiting threads.

They must be called from synchronized blocks or methods.

15. What is the ReentrantLock class in Java?

ReentrantLock is a lock that allows the same thread to acquire the lock multiple times without

deadlock. It offers more control than the synchronized keyword (e.g., fairness policy, lock polling

with tryLock()).

16. What is CountDownLatch in Java?

CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of

operations being performed by other threads complete. It is useful when you need to start multiple

threads and wait for them to finish.


17. What is CyclicBarrier and how does it differ from CountDownLatch?

CyclicBarrier allows a group of threads to wait for each other to reach a common barrier point.

Unlike CountDownLatch, it can be reused once the barrier is reached, hence 'cyclic'.

18. What is the Executor framework?

The Executor framework in Java provides a mechanism to manage thread execution via thread

pools. It simplifies concurrent task execution by separating task submission from the mechanics of

how the task is executed (i.e., thread management).

19. What is the ForkJoinPool in Java?

ForkJoinPool is a special thread pool in Java that efficiently manages and executes tasks in parallel

by breaking them into smaller subtasks (forking) and merging results (joining). It is used for

parallelism in divide-and-conquer algorithms.

20. What are Future and Callable in Java?

Callable is similar to Runnable, but it can return a result and throw exceptions.

Future represents the result of an asynchronous computation and provides methods to check if the

computation is complete, retrieve the result, or cancel the task.

21. How can thread safety be achieved in Java?

You can achieve thread safety using:

- Immutability (making objects or data immutable).

- Thread-safe collections (e.g., ConcurrentHashMap).

- Atomic classes (e.g., AtomicInteger, AtomicBoolean).

- Synchronization (synchronized, ReentrantLock).

22. What is the purpose of Thread.yield()?

Thread.yield() is a hint to the thread scheduler to give the CPU to other threads. The current thread

goes back to a 'runnable' state, and the thread scheduler decides whether to continue running it or

switch to another thread.


23. What is the difference between sleep() and wait() in Java?

sleep() pauses the thread for a specific duration without releasing any locks.

wait() causes the current thread to release the lock and wait until another thread calls notify() or

notifyAll().

24. What is the ScheduledExecutorService and how does it work?

ScheduledExecutorService allows you to schedule tasks to run after a fixed delay or periodically. It's

part of the ExecutorService interface and offers a high-level way to manage task scheduling without

manual thread management.

25. How do you handle exceptions in threads?

Uncaught exceptions in threads can be handled using the UncaughtExceptionHandler. You can set

a handler for a thread using setUncaughtExceptionHandler() or globally for all threads.

You might also like