| 52 | * need the locks in. Verify that this order does not create a deadlock (a cycle in a directed graph) |
| 53 | */ |
| 54 | public boolean declare(int ownerId, int[] resourcesInOrder) { |
| 55 | Hashtable<Integer, Boolean> touchedNodes = new Hashtable<Integer, Boolean>(); |
| 56 | |
| 57 | /* add nodes to graph */ |
| 58 | int index = 1; |
| 59 | touchedNodes.put(resourcesInOrder[0], false); |
| 60 | for (index = 1; index < resourcesInOrder.length; index++) { |
| 61 | LockNode prev = locks[resourcesInOrder[index - 1]]; |
| 62 | LockNode curr = locks[resourcesInOrder[index]]; |
| 63 | prev.joinTo(curr); |
| 64 | touchedNodes.put(resourcesInOrder[index], false); |
| 65 | } |
| 66 | |
| 67 | /* if we created a cycle, destroy this resource list and return false */ |
| 68 | if (hasCycle(touchedNodes, resourcesInOrder)) { |
| 69 | for (int j = 1; j < resourcesInOrder.length; j++) { |
| 70 | LockNode p = locks[resourcesInOrder[j - 1]]; |
| 71 | LockNode c = locks[resourcesInOrder[j]]; |
| 72 | p.remove(c); |
| 73 | } |
| 74 | return false; |
| 75 | } |
| 76 | |
| 77 | /* No cycles detected. Save the order that was declared, so that we can verify that the |
| 78 | * process is really calling the locks in the order it said it would. */ |
| 79 | LinkedList<LockNode> list = new LinkedList<LockNode>(); |
| 80 | for (int i = 0; i < resourcesInOrder.length; i++) { |
| 81 | LockNode resource = locks[resourcesInOrder[i]]; |
| 82 | list.add(resource); |
| 83 | } |
| 84 | lockOrder.put(ownerId, list); |
| 85 | |
| 86 | return true; |
| 87 | } |
| 88 | |
| 89 | /* Get the lock, verifying first that the process is really calling the locks in the order |
| 90 | * it said it would. */ |