Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. public void acquire(Transaction transaction, String tableName, LockType lockType)
  2.             throws IllegalArgumentException {
  3.         if (!transaction.getStatus().equals(Transaction.Status.Running)) {
  4.             throw new IllegalArgumentException();
  5.         }
  6.  
  7.         TableLock tLock = tableToTableLock.get(tableName);
  8.         if (tLock == null || tLock.lockOwners.isEmpty()) {
  9.             tLock = new TableLock(lockType);
  10.             tLock.lockOwners.add(transaction);
  11.             tableToTableLock.put(tableName, tLock);
  12.             return;
  13.         }
  14.  
  15.         boolean granted = true;
  16.         boolean promote = false;
  17.         for (Request r : tLock.requestersQueue) {
  18.             if (r.transaction.equals(transaction)) {
  19.                 if (r.lockType.equals(LockType.Exclusive) || r.lockType.equals(lockType))
  20.                     throw new IllegalArgumentException();
  21.                 else {
  22.                     if (tLock.requestersQueue.size() == 1) {
  23.                         // promotion granted
  24.                         tLock.lockType = LockType.Exclusive;
  25.                         tableToTableLock.put(tableName, tLock);
  26.                         return;
  27.                     } else {
  28.                         promote = true;
  29.                     }
  30.                 }
  31.             } else if (r.lockType.equals(LockType.Exclusive) && tLock.lockOwners.contains(r.transaction)) {
  32.                 transaction.sleep();
  33.                 granted = false;
  34.                 break;
  35.             } else if (r.lockType.equals(LockType.Shared) && tLock.lockOwners.contains(r.transaction) && lockType.equals(LockType.Exclusive)) {
  36.                 transaction.sleep();
  37.                 granted = false;
  38.                 break;
  39.             }
  40.         }
  41.  
  42.         if (granted) {
  43.             tLock.lockType = lockType;
  44.             tLock.lockOwners.add(transaction);
  45.         } else {
  46.             // TODO check lockType waitDie woundWait
  47.             if (promote)
  48.                 tLock.requestersQueue.addFirst(new Request(transaction, lockType));
  49.             else
  50.                 tLock.requestersQueue.add(new Request(transaction, lockType));
  51.         }
  52.  
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement