3

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 ?

Carbonizer
  • 1,915
  • 2
  • 19
  • 22
  • Could you be more specific? Why are you worried about deadlock? Deadlock is only going to occur if thread A is has resource a locked and is waiting on resource b, and thread B has resource b locked and is waiting on resource a, or a similar scenario. – Gabriel Reid Dec 15 '10 at 15:29
  • Is this just a generic question or do you have a particular problem? The generic answer would propably be to code it accordingly, draw a diagram or something and evaluate all possibilities. – thejh Dec 15 '10 at 15:29
  • 5
    Always acquire the resources in the same order :) – Nikolai Fetissov Dec 15 '10 at 15:32
  • Please more detail. Which resources is every thread going to use? Only one, all of them, a subset? – Eduard Wirch Dec 15 '10 at 15:32
  • @Nikolai: should be an answer. – Eduard Wirch Dec 15 '10 at 15:33

3 Answers3

7

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.

Community
  • 1
  • 1
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
1

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.

Kumar Abhishek
  • 3,004
  • 33
  • 29
0

Can you give some more details?

Having a counter protected by "synchronized" may be all that is required.

Jaydee
  • 4,138
  • 1
  • 19
  • 20