How can we detect and avoid deadlock in Java?
A deadlock can appear almost when the processes share the resources. To detect the deadlock, the wait-for graph should be maintained, and the system invokes an algorithm periodically that searches for cycles in the wait-for graph.
How to avoid deadlock:
- Avoid nested locks: The main reason for the deadlock is giving locks to multiple threads. You should avoid giving the locks to multiple threads when you have already given them to one.
- Avoiding unnecessary locks: We can lock only the required members. To have a lock unnecessarily can lead to a deadlock.
- Use Thread. Join (): Deadlock condition appears when one Thread is waiting for another to finish. In case this condition arises, we can use the Thread. Join () with the maximum time the execution will take.
BY Best Interview Question ON 03 May 2022