Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Question, how to prevent n threads n resources deadlock in java

This question was asked in an interview and the approach taken architecturally to solve this problem at high level was being judged. In Java, how can this be solved -->N threads .. n resources .. what protocol do you use to ensure no deadlocks occur?

So, can someone let me know the most optimal approach ? making all the methods synchronized can make the system deadlocked, so how to solve this problem ?

like image 857
Carbonizer Avatar asked Oct 16 '25 11:10

Carbonizer


2 Answers

Probably they're looking for lock ordering. That is, if you use more than one lock and more than one thread, you must ensure that the locks are always obtained in the same order. Otherwise a deadlock is just a matter of time.

like image 102
Joonas Pulakka Avatar answered Oct 19 '25 12:10

Joonas Pulakka


N Threads can Access N Resources if there is no Sharing without any problem, The challenge Comes when there is a Resource Shared among different threads.

Lets us take example of Printer,Scanner,Oven,Coffee Machine In our office we consider them as Resources and Employees as Threads so what happens if 2 Resources say Employee John and Christen comes for Coffee they Stand in a Queue There is no Parallel processing by Coffee Machine, Same with Printer Employee Venkat submits a printing job at the same time Jame also submits printing job it goes to a Job Queue.

So you have to implement Blocking Queue and Resources as Consumers.

In case if you work with Semaphores , you can control no of threads entering to your critical section.

like image 38
Kumar Abhishek Avatar answered Oct 19 '25 13:10

Kumar Abhishek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!