Java_Multithreading_Interview_Problems
Java_Multithreading_Interview_Problems
What are the differences between Thread, Runnable, and Callable in Java?
Thread:
Represents an actual thread of execution.
Extending Thread class allows overriding run(), but limits inheritance flexibility.
Runnable:
Functional interface with run() method, does not return result or throw checked
exceptions.
Preferred when task doesn’t need to return a value.
Callable:
Callable<T> has call() method that returns a value and can throw checked exceptions.
Often used with ExecutorService and Future for result-bearing tasks.
Use Callable when result or exception handling is needed.
What are the risks of using synchronized and how can deadlocks be avoided?
synchronized blocks or methods ensure mutual exclusion but introduce potential risks:
Deadlocks: threads waiting on locks held by each other.
Reduced concurrency and throughput.
Priority inversion or thread starvation in high-contention scenarios.
Strategies to avoid deadlocks:
Always acquire locks in a consistent global order.
Avoid holding multiple locks at once unless necessary.
Use tryLock() with timeout (from ReentrantLock) to detect deadlock potential.
Favor higher-level concurrency utilities when possible (e.g., java.util.concurrent).