Example #1
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();
    }
  }
Example #2
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;
  }
Example #3
0
  /*
   *
   *   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);
          }
        }
      }
    }
  }
 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);
       }
     }
   }
 }
Example #5
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);
  }
Example #6
0
  // 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();
    }
  }
 public void release() {
   lock.lock();
   try {
     if (counter > 0) --counter;
   } finally {
     lock.unlock();
   }
 }
Example #8
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();
   }
 }
 public void acquire() throws InterruptedException {
   lock.lock();
   try {
     while (!(counter < permits)) queue.await();
     ++counter;
   } finally {
     lock.unlock();
   }
 }
Example #10
0
 public void resetGenerator(CharacterSource newGenerator) {
   try {
     scoreLock.lock();
     if (generator != null) generator.removeCharacterListener(this);
     generator = newGenerator;
     if (generator != null) generator.addCharacterListener(this);
   } finally {
     scoreLock.unlock();
   }
 }
Example #11
0
 public void resetTypist(CharacterSource newTypist) {
   try {
     scoreLock.lock();
     if (typist != null) typist.removeCharacterListener(this);
     typist = newTypist;
     if (typist != null) typist.addCharacterListener(this);
   } finally {
     scoreLock.unlock();
   }
 }
  public void setDone(boolean b) {
    try {
      lock.lock();
      done = b;

      if (!done) cv.signal();
    } finally {
      lock.unlock();
    }
  }
 public synchronized void increment() {
   lock.lock();
   try {
     p.incrementX();
     p.incrementY();
     store(getPair());
   } finally {
     lock.unlock();
   }
 }
  /**
   * Sets the value of statistic
   *
   * @param stat the name of the statistic
   * @param value the value of the statistic
   */
  public void setStat(String stat, Object value) {
    Lock lock = this.lock.writeLock();

    lock.lock();
    try {
      unlockedSetStat(stat, value);
    } finally {
      lock.unlock();
    }
  }
 private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
   waitLock.lock();
   waiter++;
   try {
     hasAvailableConnection.await(timeout, unit);
   } finally {
     waiter--;
     waitLock.unlock();
   }
 }
Example #16
0
 public void resetScore() {
   try {
     scoreLock.lock();
     score = 0;
     char2type = -1;
     setScore();
   } finally {
     scoreLock.unlock();
   }
 }
  /** Notify the worker that new entry to delete appeared. */
  void signal() {
    lock.lock();

    try {
      force = true;

      cond.signalAll();
    } finally {
      lock.unlock();
    }
  }
  private void signalAllAvailableConnection() {
    // Quick check if it's worth signaling to avoid locking
    if (waiter == 0) return;

    waitLock.lock();
    try {
      hasAvailableConnection.signalAll();
    } finally {
      waitLock.unlock();
    }
  }
    public void deposit(int amount) {
      lock.lock(); // Acquire the lock
      try {
        balance += amount;
        System.out.println("Deposit " + amount + "\t\t\t\t\t" + getBalance());

        newDeposit.signalAll();
      } finally {
        lock.unlock(); // Release the lock
      }
    }
Example #20
0
 public Integer take() {
     lock.lock();
     try {
         while (q.size() == 0) {
             empty.await();
         }
         if (q.size() = limit) {
             full.signalAll();
         }
         return q.poll();
     }catch(Exception e) {
 public int nextInt(int n) {
   lock.lock();
   try {
     int s = seed;
     seed = calculateNext(s);
     int remainder = s % n;
     return remainder > 0 ? remainder : remainder + n;
   } finally {
     lock.unlock();
   }
 }
  /** {@inheritDoc} */
  @Override
  public long get() throws GridException {
    checkRemoved();

    lock.lock();

    try {
      return locVal;
    } finally {
      lock.unlock();
    }
  }
  /**
   * Returns the value of the statistic.
   *
   * @param stat the name of the statistic.
   * @return the value.
   */
  public Object getStat(String stat) {
    Lock lock = this.lock.readLock();
    Object value;

    lock.lock();
    try {
      value = stats.get(stat);
    } finally {
      lock.unlock();
    }
    return value;
  }
  /**
   * Returns the map with the names of the statistics and their values.
   *
   * @return the map with the names of the statistics and their values.
   */
  public Map<String, Object> getStats() {
    Lock lock = this.lock.readLock();
    Map<String, Object> stats;

    lock.lock();
    try {
      stats = new HashMap<String, Object>(this.stats);
    } finally {
      lock.unlock();
    }
    return stats;
  }
  /**
   * Set local batch size for this sequences.
   *
   * @param size Sequence batch size. Must be more then 0.
   */
  @Override
  public void batchSize(int size) {
    A.ensure(size > 0, " Batch size can't be less then 0: " + size);

    lock.lock();

    try {
      batchSize = size;
    } finally {
      lock.unlock();
    }
  }
Example #26
0
 /* Devolve lista com o tipo de tarefas em desenvolvimento */
 public HashMap<Integer, String> listTaskRunnig() {
   HashMap<Integer, String> tasklist = new HashMap<>();
   lock.lock();
   try {
     for (Map.Entry<Integer, String> entry : this.tasksRunning.entrySet()) {
       tasklist.put(entry.getKey(), entry.getValue());
     }
     return tasklist;
   } finally {
     lock.unlock();
   }
 }
 public void increment() {
   Pair temp;
   lock.lock();
   try {
     p.incrementX();
     p.incrementY();
     temp = getPair();
   } finally {
     lock.unlock();
   }
   store(temp);
 }
Example #28
0
  /*Devolve uma lista do stock corrente*/
  public HashMap<String, Integer> listStock() {
    HashMap<String, Integer> liststock = new HashMap<>();

    lock.lock();
    try {
      for (Map.Entry<String, Product> entry : this.warehouse.getStock().entrySet()) {
        liststock.put(entry.getKey(), entry.getValue().getQuantity());
      }
      return liststock;
    } finally {
      lock.unlock();
    }
  }
  /** {@inheritDoc} */
  @Override
  public void close() throws GridException {
    closeLock.lock();

    try {
      if (routineId == null)
        throw new IllegalStateException("Can't cancel query that was not executed.");

      ctx.kernalContext().continuous().stopRoutine(routineId).get();
    } finally {
      closeLock.unlock();
    }
  }
Example #30
0
  /* Devolve lista com o tipo de tarefas */
  public List<String> listTask() {
    ArrayList<String> tasklist = new ArrayList<>();

    lock.lock();
    try {
      for (Task task : this.tasks.values()) {
        tasklist.add(task.getType());
      }
      return tasklist;
    } finally {
      lock.unlock();
    }
  }