/**
   * Refresh locks held by the authorization <code>authID</code>.
   *
   * <p>(remember that the lock may have expired)
   *
   * @param authID Authorization identifing Lock to refresh
   * @param transaction Transaction with authorization for lockID
   * @return <code>true</code> if lock was found and refreshed
   * @throws IOException If transaction not authorized to refresh authID
   * @throws IllegalArgumentException If authID or transaction not provided
   */
  public synchronized boolean refresh(String authID, Transaction transaction) throws IOException {
    if (authID == null) {
      throw new IllegalArgumentException("lockID required");
    }

    if ((transaction == null) || (transaction == Transaction.AUTO_COMMIT)) {
      throw new IllegalArgumentException(
          "Tansaction required (with authorization for " + authID + ")");
    }

    Lock lock;
    boolean refresh = false;

    for (Iterator i = allLocks().iterator(); i.hasNext(); ) {
      lock = (Lock) i.next();

      if (lock.isExpired()) {
        i.remove();
      } else if (lock.isMatch(authID)) {
        if (lock.isAuthorized(transaction)) {
          lock.refresh();
          refresh = true;
        } else {
          throw new IOException("Not authorized to refresh " + lock);
        }
      }
    }

    return refresh;
  }
  /**
   * Lock for typeName & featureID if it exists.
   *
   * <p>This method will not return expired locks.
   *
   * @param typeName
   * @param featureID
   * @return Lock if exists, or null
   */
  protected Lock getLock(String typeName, String featureID) {
    Map locks = locks(typeName);
    // LOGGER.info("checking for lock " + typeName + ", " + featureID
    //    + " in locks " + locks);

    synchronized (locks) {
      if (locks.containsKey(featureID)) {
        Lock lock = (Lock) locks.get(featureID);

        if (lock.isExpired()) {
          locks.remove(featureID);
          // LOGGER.info("returning null");

          return null;
        } else {
          // LOGGER.info("returing " + lock);

          return lock;
        }
      } else {
        // LOGGER.info("locks did not contain key, returning null");

        // not found
        return null;
      }
    }
  }
Exemple #3
0
    public void run() {

      otherMethod(l1);
      otherMethod(l2);
      l1.unlock();
      l2.unlock();
    }
Exemple #4
0
 public Q(int limit) {
     this.q = new LinkedList<>();
     this.limit = limit;
     this.lock = new ReentrantLock();
     this.full = lock.newCondition();
     this.empty = lock.newCondition();
 }
Exemple #5
0
  /*
   * Termina a realização da Tarefa.
   * Retorna true se foi terminada com sucesso false caso contrário
   */
  public boolean endTask(String id) throws InterruptedException {
    Map<String, Integer> objectsToSupply;
    String type;
    lock.lock();
    try {
      if (!this.tasksRunning.containsKey(Integer.valueOf(id))) {
        return false;
      } else {
        type = this.tasksRunning.get(Integer.valueOf(id));
        objectsToSupply = this.tasks.get(type).getObjects();
      }
    } finally {
      lock.unlock();
    }

    // Supply de todos os objetos
    for (Map.Entry<String, Integer> entry : objectsToSupply.entrySet()) {
      warehouse.supply(entry.getKey(), entry.getValue());
    }

    lock.lock();
    try {
      this.tasksRunning.remove(Integer.valueOf(id));
      this.tasks.get(type).signalP();
    } finally {
      lock.unlock();
    }

    return true;
  }
Exemple #6
0
  /** Do the real work of releaseAndFindNotifyTargets */
  Set<Locker> releaseAndFindNotifyTargetsInternal(long nodeId, Locker locker, int lockTableIndex) {
    Map<Long, Lock> lockTable = lockTables[lockTableIndex];
    Lock useLock = lockTable.get(nodeId);
    if (useLock == null) {
      useLock = lockTable.get(Long.valueOf(nodeId));
    }

    if (useLock == null) {
      /* Lock doesn't exist. */
      return null;
    }

    Set<Locker> lockersToNotify = useLock.release(locker, memoryBudget, lockTableIndex);
    if (lockersToNotify == null) {
      /* Not owner. */
      return null;
    }

    /* If it's not in use at all, remove it from the lock table. */
    if ((useLock.nWaiters() == 0) && (useLock.nOwners() == 0)) {
      lockTables[lockTableIndex].remove(nodeId);
      if (useLock.isThin()) {
        memoryBudget.updateLockMemoryUsage(REMOVE_TOTAL_THINLOCKIMPL_OVERHEAD, lockTableIndex);
      } else {
        memoryBudget.updateLockMemoryUsage(REMOVE_TOTAL_LOCKIMPL_OVERHEAD, lockTableIndex);
      }
    }

    return lockersToNotify;
  }
Exemple #7
0
  static void AdultItinerary() {
    System.out.println("--- called adult itinerary");

    /* This is where you should put your solutions. Make calls
     to the BoatGrader to show that it is synchronized. For
     example:
         bg.AdultRowToMolokai();
     indicates that an adult has rowed the boat across to Molokai
    */

    pilotLock.acquire();

    // While the boat is not at Oahu or there are more than 2 children on Oahu,
    // put the adult on Oahu thread to sleep (because we wouldn't send and adult in
    // these scenarios).
    while (boatLocation != 0 || numChildrenOnOahu >= 2) {
      System.out.println("--- can't send an adult to Molokai right now");
      adultReadyAtOahu.sleep();
    }

    System.out.println("--- sending an adult to Molokai");
    numAdultsOnOahu--; // an adult is rowing Oahu --> Molokai, so decrement
    bg.AdultRowToMolokai();
    numAdultsOnMolokai++; // adult has rowed over, so increment
    printState();
    boatLocation = 1; // boat is now at Molokai
    childReadyAtMolokai.wake(); // wake up child at Molokai since it's now their turn			

    pilotLock.release();
  }
  synchronized int unlockReference(LockTable lset, Lockable ref, Object qualifier, Object group) {

    // look for locks matching our reference and qualifier.
    HashMap dl = (HashMap) groups.get(group);
    if (dl == null) return 0;

    Lock lockInGroup = lset.unlockReference(this, ref, qualifier, dl);
    if (lockInGroup == null) {
      return 0;
    }

    if (lockInGroup.getCount() == 1) {

      if (dl.isEmpty()) {
        groups.remove(group);
        saveGroup(dl);
        if ((callbackGroup != null) && group.equals(callbackGroup)) {
          nextLimitCall = limit;
        }
      }

      return 1;
    }

    // the lock item will be left in the group
    lockInGroup.count--;
    dl.put(lockInGroup, lockInGroup);
    return 1;
  }
 public void run() {
   while (true) {
     LinkedList<PacketCallbackStruct> list = null;
     try {
       queuedPacketCallbacksLock.lock();
       try {
         queuedPacketCallbacksNotEmpty.await();
       } catch (Exception e) {
         Log.error(
             "RDPServer.PacketCallbackThread: queuedPacketCallbacksNotEmpty.await() caught exception "
                 + e.getMessage());
       }
       list = queuedPacketCallbacks;
       queuedPacketCallbacks = new LinkedList<PacketCallbackStruct>();
     } finally {
       queuedPacketCallbacksLock.unlock();
     }
     if (Log.loggingNet)
       Log.net("RDPServer.PacketCallbackThread: Got " + list.size() + " queued packets");
     for (PacketCallbackStruct pcs : list) {
       try {
         callbackProcessPacket(pcs.cb, pcs.con, pcs.packet);
       } catch (Exception e) {
         Log.exception("RDPServer.PacketCallbackThread: ", e);
       }
     }
   }
 }
Exemple #10
0
  /** Test if this module is working. */
  public static void selfTest() {

    System.out.print("Enter Condition2.selfTest\n");

    Lock lock = new Lock();
    Condition2 condition = new Condition2(lock);

    KThread t[] = new KThread[10];
    for (int i = 0; i < 10; i++) {
      t[i] = new KThread(new Condition2Test(lock, condition));
      t[i].setName("Thread" + i).fork();
    }

    KThread.yield();

    lock.acquire();

    System.out.print("condition.wake();\n");
    condition.wake();

    System.out.print("condition.wakeAll();\n");
    condition.wakeAll();

    lock.release();

    System.out.print("Leave Condition2.selfTest\n");

    t[9].join();
  }
Exemple #11
0
  /*
   * Inicia a realização de uma Tarefa.
   * Retorna o ID se foi iniciada com sucesso -1 caso contrário
   */
  public int beginTask(String type) {
    Map<String, Integer> objectsToConsume;
    lock.lock();
    try {
      if (!this.tasks.containsKey(type)) return -1;
      else {
        objectsToConsume = this.tasks.get(type).getObjects();
      }
    } finally {
      lock.unlock();
    }

    try {
      warehouse.consume(objectsToConsume);
    } catch (Exception e) {
      return -1;
    }

    lock.lock();
    try {
      countID++;
      this.tasksRunning.put(countID, type);
      return countID; // Retornar o ID da tarefa
    } finally {
      lock.unlock();
    }
  }
Exemple #12
0
  public LockAttemptResult lock(
      LockType requestType,
      Locker locker,
      boolean nonBlockingRequest,
      MemoryBudget mb,
      int lockTableIndex)
      throws DatabaseException {

    if (this.locker != null && this.locker != locker) {
      /* Lock is already held by someone else so mutate. */
      Lock newLock = new LockImpl(new LockInfo(this.locker, this.lockType));
      return newLock.lock(requestType, locker, nonBlockingRequest, mb, lockTableIndex);
    }

    LockGrantType grant = null;
    if (this.locker == null) {
      this.locker = locker;
      this.lockType = requestType;
      grant = LockGrantType.NEW;
    } else {

      /* The requestor holds this lock.  Check for upgrades. */
      LockUpgrade upgrade = lockType.getUpgrade(requestType);
      if (upgrade.getUpgrade() == null) {
        grant = LockGrantType.EXISTING;
      } else {
        LockType upgradeType = upgrade.getUpgrade();
        assert upgradeType != null;
        this.lockType = upgradeType;
        grant = (upgrade.getPromotion() ? LockGrantType.PROMOTION : LockGrantType.EXISTING);
      }
    }
    return new LockAttemptResult(this, grant, false);
  }
Exemple #13
0
  public Lock transferMultiple(
      Long nodeId, Locker currentLocker, Locker[] destLockers, MemoryBudget mb, int lockTableIndex)
      throws DatabaseException {

    Lock newLock = new LockImpl(new LockInfo(this.locker, this.lockType));
    return newLock.transferMultiple(nodeId, currentLocker, destLockers, mb, lockTableIndex);
  }
Exemple #14
0
  /** Do the real work of dumpLockTableInternal. */
  void dumpLockTableInternal(StatGroup tableStats, int i, boolean clear) {
    StatGroup oneTable = new StatGroup("Single lock table", "Temporary stat group");

    IntStat totalLocks = new IntStat(oneTable, LOCK_TOTAL);
    IntStat waiters = new IntStat(oneTable, LOCK_WAITERS);
    IntStat owners = new IntStat(oneTable, LOCK_OWNERS);
    IntStat readLocks = new IntStat(oneTable, LOCK_READ_LOCKS);
    IntStat writeLocks = new IntStat(oneTable, LOCK_WRITE_LOCKS);

    Map<Long, Lock> lockTable = lockTables[i];
    totalLocks.add(lockTable.size());

    for (Lock lock : lockTable.values()) {
      waiters.add(lock.nWaiters());
      owners.add(lock.nOwners());

      /* Go through all the owners for a lock. */
      for (LockInfo info : lock.getOwnersClone()) {
        if (info.getLockType().isWriteLock()) {
          writeLocks.increment();
        } else {
          readLocks.increment();
        }
      }
    }
    tableStats.addAll(oneTable);
  }
  // the landing method
  public void landing(int flight_num, int wind) throws InterruptedException {
    L.lock();

    try {
      // if turn is set to takeoff, then wait
      if (turn == 0) {
        C.await();
      }

      wind_direction = wind;
      RunwaySystem();

      System.out.println(
          "Flight "
              + flight_num
              + " is cleared for landing on runway "
              + runway_number
              + runway_direction);
      System.out.println("Flight " + flight_num + " has arrived. The runway is now clear.");
      System.out.println("===========>\n");

      // set the turn for takeoff
      turn = 0;
      C.signalAll();
    } finally {
      L.unlock();
    }
  }
Exemple #16
0
 /** ロック開放後同一カテゴリとキーでロック取得可能. */
 @Test
 public void ロック開放後同一カテゴリとキーでロック取得可能() {
   Lock lock = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null);
   lock.release();
   Lock lock2 = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null);
   assertNotNull(lock2);
   lock2.release();
 }
 /** Handle the timeout of a previous lock mapped to this key */
 protected void handleLockExpiry(Object key, Lockable lock) {
   LOG.expired(key);
   long ts = getInternalRegion().nextTimestamp() + getInternalRegion().getTimeout();
   // create new lock that times out immediately
   Lock newLock = new Lock(ts, uuid, nextLockId.getAndIncrement(), null);
   newLock.unlock(ts);
   getInternalRegion().put(key, newLock);
 }
Exemple #18
0
 /*
  * @return true if this site has given such a lock, @testLock
  */
 public boolean isActiveLockExist(Lock testLock) {
   for (Lock lock : this.activeLocks) {
     if (lock.isEqual(testLock)) {
       return true;
     }
   }
   return false;
 }
 public void release() {
   lock.lock();
   try {
     if (counter > 0) --counter;
   } finally {
     lock.unlock();
   }
 }
Exemple #20
0
 /* Termina a sessão de um utilizador */
 public void logout(String nick) {
   lock.lock();
   try {
     this.users.get(nick).setAtivo(false);
   } finally {
     lock.unlock();
   }
 }
 /** Test ensureValid returns true after acquire */
 public void testValidAfterAcquire() throws IOException {
   Path tempPath = createTempDir();
   Directory dir = getDirectory(tempPath);
   Lock l = dir.obtainLock("commit");
   l.ensureValid(); // no exception
   l.close();
   dir.close();
 }
  /**
   * Release locks held by the authorization <code>authID</code>.
   *
   * <p>(remember that the lock may have expired)
   *
   * @param authID Authorization identifing Lock to release
   * @param transaction Transaction with authorization for lockID
   * @return <code>true</code> if lock was found and released
   * @throws IOException If transaction not authorized to release authID
   * @throws IllegalArgumentException If authID or transaction not provided
   */
  public boolean release(String authID, Transaction transaction) throws IOException {
    // LOGGER.info("release called on lock: " + authID + ", trans: "
    //  + transaction);

    if (authID == null) {
      throw new IllegalArgumentException("lockID required");
    }

    if ((transaction == null) || (transaction == Transaction.AUTO_COMMIT)) {
      throw new IllegalArgumentException(
          "Tansaction required (with authorization for " + authID + ")");
    }

    Lock lock;
    boolean release = false;

    // This could be done more efficiently, and perhaps cleaner,
    // but these maps within a map are just nasty.  The previous way of
    // calling iterator.remove() didn't actually remove anything, as it
    // was only iterating through the values of a map, which I believe
    // java just copies, so it's immutable.  Or perhaps we just moved
    // through too many iterator layers...
    for (Iterator i = lockTables.values().iterator(); i.hasNext(); ) {
      Map fidMap = (Map) i.next();
      Set unLockedFids = new HashSet();

      for (Iterator j = fidMap.keySet().iterator(); j.hasNext(); ) {
        String fid = (String) j.next();
        lock = (Lock) fidMap.get(fid);
        // LOGGER.info("checking lock " + lock + ", is match "
        //    + lock.isMatch(authID));

        if (lock.isExpired()) {
          unLockedFids.add(fid);

          // fidMap.remove(fid); concurrent modification error.
        } else if (lock.isMatch(authID)) {
          // LOGGER.info("matches, is authorized: "
          //    + lock.isAuthorized(transaction));

          if (lock.isAuthorized(transaction)) {
            unLockedFids.add(fid);

            // fidMap.remove(fid);
            release = true;
          } else {
            throw new IOException("Not authorized to release " + lock);
          }
        }
      }

      for (Iterator k = unLockedFids.iterator(); k.hasNext(); ) {
        fidMap.remove(k.next());
      }
    }

    return release;
  }
  /** Handle the timeout of a previous lock mapped to this key */
  protected void handleLockExpiry(SessionImplementor session, Object key, Lockable lock) {
    LOG.info("Cached entry expired : " + key);

    long ts = getInternalRegion().nextTimestamp() + getInternalRegion().getTimeout();
    // create new lock that times out immediately
    Lock newLock = new Lock(ts, uuid, nextLockId.getAndIncrement(), null);
    newLock.unlock(ts);
    getInternalRegion().put(session, key, newLock);
  }
Exemple #24
0
 /** 違うカテゴリであれば同キー名での連続取得が可能. */
 @Test
 public void 違うカテゴリであれば同キー名での連続取得が可能() {
   Lock lockOData = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null);
   Lock lockDav = LockManager.getLock(Lock.CATEGORY_DAV, "aaa", null, null);
   assertNotNull(lockOData);
   assertNotNull(lockDav);
   lockDav.release();
   lockOData.release();
 }
 public void acquire() throws InterruptedException {
   lock.lock();
   try {
     while (!(counter < permits)) queue.await();
     ++counter;
   } finally {
     lock.unlock();
   }
 }
  /*
   *
   *   Date      By	Description
   * MM/DD/YYYY
   * ----------  --	-----------
   * 11/17/2003  INB	Ensure that no <code>Lock</code> is set on an
   *			<code>InterruptedException</code>.  Clear the thread on
   *			release of the primary <code>Lock</code>.
   * 11/12/2003  INB	Created.
   *
   */
  final void lockRead(String locationI) throws java.lang.InterruptedException {
    boolean grabbed = false;

    try {
      try {
        // Look for an existing read lock.
        Lock readLock;

        readLock = (Lock) getReadLocks().find(Thread.currentThread());

        if (readLock != null) {
          // If there is a read lock already, just apply it again.
          readLock.lock(locationI, true);

        } else {
          // If one doesn't exist, create one.
          readLock = new Lock(this);
          readLock.lock(locationI, true);
          // Grab the primary lock before adding the lock to the
          // door. This ensures that there is no write lock active or
          // waiting. Release the primary lock after the read lock is
          // created.
          grabbed = true;
          try {
            getPrimaryLock().grab(locationI, true, false);
          } catch (java.lang.InterruptedException e) {
            readLock.unlock();
            throw e;
          }
          synchronized (getReadLocks()) {
            getReadLocks().add(readLock);
          }
          synchronized (getPrimaryLock()) {
            getPrimaryLock().release();
            if (getPrimaryLock().count == 0) {
              getPrimaryLock().setThread(null);
            }
            grabbed = false;
          }
        }

      } catch (com.rbnb.utility.SortException e) {
        throw new com.rbnb.compat.InternalError();
      }

    } finally {
      if (grabbed) {
        // Release the primary lock if we got it.
        synchronized (getPrimaryLock()) {
          getPrimaryLock().release();
          if (getPrimaryLock().count == 0) {
            getPrimaryLock().setThread(null);
          }
        }
      }
    }
  }
  private void sessionHeartBeat(String id, String sessionId) {
    Lock lock = locks.get(id);

    if (lock.getSessionId().equals(sessionId)) {
      lock.setLastHeartBeat(new Date().getTime());
    } else {
      // who are you??
    }
  }
  public void stopSession(String id, String sessionId, PrintWriter writer) {
    Lock lock = locks.get(id);

    try {
      lock.unlock(sessionId);
    } finally {
      writer.flush();
    }
  }
  public void setDone(boolean b) {
    try {
      lock.lock();
      done = b;

      if (!done) cv.signal();
    } finally {
      lock.unlock();
    }
  }
  /** Handle the timeout of a previous lock mapped to this key */
  protected void handleLockExpiry(Object key, Lockable lock) {
    logger.trace("handleLockExpiry Key=[{}] Lockable=[{}}]", key, lock);

    // create new lock that times out immediately
    final long timeStamp = region.nextTimestamp() + region.getTimeout();
    final Lock newLock = new Lock(timeStamp, uuid, nextLockId.getAndIncrement(), null);
    newLock.unlock(timeStamp);

    region.put(key, newLock);
  }