Problem
Design a class which provides a lock only if there are no possible deadlocks.
Solution
Deadlock will occur with a lock only if the locks can be held in a circular fashion; that is, if you define an ordering < on locks such that A < B only if lock A can be held with lock B also held, then< is not a strict partial ordering. For example, if thread 1 tries to acquire lock A and then lock B, while thread 2 tries to acquire lock B and then lock A, then A < B and B < A, so < is not a strict partial ordering. Indeed, deadlock can occur if threads 1 and 2 each get locks A and B, respectively, then try to acquire the other lock.
So, a class can create a deadlock, by acquiring the control of the entire set
of related locks that might be involved in such deadlocks. It can then,
for example, require they be taken in some specific order (e.g.
alphabetic ordering based on a name associated with each lock, arbitrary
unique integers hardcoded in the source).
For our solution, we implement a wait / die deadlock prevention scheme.
Wait-die scheme: It is a non-preemptive technique for deadlock prevention. When transaction Ti requests a data item currently held by Tj, Ti is allowed to wait only if it has a timestamp smaller than that of Tj (That is Ti is older than Tj), otherwise Ti is rolled back (dies)
For example:
Suppose that transaction T22, T23, T24 have time-stamps 5, 10 and 15 respectively. If T22 requests a data item held by T23 then T22 will wait. If T24 requests a data item held by T23, then T24 will be rolled back.
(definition taken from code bank.)
Java code
class MyThread extends Thread { long time; ArrayList<Resource> res = new ArrayList<Resource>(); public ArrayList<Resource> getRes() { return res; } @Override public void run() { // Run infinitely time = System.currentTimeMillis(); int count = 0; while (true) { if (count < 4) { if (Question.canAcquireResource(this, Question.r[count])) { <span class="skimlinks-unlinked">res.add(Question.r</span>[count]); count++; <span class="skimlinks-unlinked">System.out.println("Resource</span>: [" + Question.r[count - 1].getId() + "] acquired by thread: [" + this.getName() + "]"); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } else { <span class="skimlinks-unlinked">this.stop</span>(); } } } public long getTime() { return time; } public void setRes(ArrayList<Resource> res) { <span class="skimlinks-unlinked">this.res</span> = res; } MyThread(String name) { super(name); } }
Thanks
References
"If T24 requests a data item held by T23, then T24 will be rolled back." completely wrong and inversed understanding
ReplyDeletecan you please elaborate a bit more. (Apologies for getting back so late)
Delete