Interview Question, how to prevent n threads n resources deadlock in java
This question wa开发者_JS百科s 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 ?
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.
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.
Can you give some more details?
Having a counter protected by "synchronized" may be all that is required.
精彩评论