public void comer(int id) {
   accessLock.lock(); // bloqueia a mesa
   int x = 0, contador = 0;
   boolean teste = false;
   try {
     do {
       for (int i = 0; i < feitos.size(); i++) {
         if (feitos.get(i).getId_cliente() == id) {
           x = i;
           teste = true;
         }
       }
       if (!produtos.isEmpty() && !teste) { // se não tiver itens feitos
         System.out.printf("Cliente[%d] aguardando\n", id);
         comer.await(); // bloqueia alguem comer
       }
       for (int i = 0; i < feitos.size(); i++) {
         if (feitos.get(i).getId_cliente() == id) {
           x = i;
           teste = true;
         }
       }
     } while (!teste && !produtos.isEmpty());
     if (teste) {
       feitos.get(x).setStatus("CONSUMIDO");
       System.out.printf("O Cliente[%d] consumiu o item[%d]\n", id, feitos.get(x).getId_pedido());
       feitos.remove(x);
       cozinhar.signalAll(); // libera a producao de mais itens
     }
   } catch (InterruptedException e) {
     e.printStackTrace();
   } finally {
     accessLock.unlock(); // libera  a mesa
   }
 }
Example #2
0
  private void dispatchMessages(Dispatch<? super T> dispatch) {
    while (true) {
      T message = null;
      lock.lock();
      try {
        while (state != State.Stopped && queue.isEmpty()) {
          try {
            condition.await();
          } catch (InterruptedException e) {
            throw new UncheckedException(e);
          }
        }
        if (!queue.isEmpty()) {
          message = queue.remove();
          condition.signalAll();
        }
      } finally {
        lock.unlock();
      }

      if (message == null) {
        // Have been stopped and nothing to deliver
        return;
      }

      dispatch.dispatch(message);
    }
  }
 /**
  * Forces the current thread to wait for the voting to complete if it is responsible for creating
  * the Saga. As soon as an invocation has been recorded, the waiting thread is released.
  *
  * @param didInvocation indicates whether the current processor found a Saga to process
  * @param totalVotesExpected The total number of processors expected to cast a vote
  * @param isSagaOwner Indicates whether the current processor "owns" the to-be-created saga
  *     instance.
  * @return <code>true</code> if the current processor should create the new instance, <code>false
  *     </code> otherwise.
  */
 public boolean waitForSagaCreationVote(
     final boolean didInvocation, final int totalVotesExpected, final boolean isSagaOwner) {
   votingLock.lock();
   try {
     invocationDetected = invocationDetected || didInvocation;
     castVotes++;
     while (isSagaOwner && !invocationDetected && castVotes < totalVotesExpected) {
       try {
         allVotesCast.await();
       } catch (InterruptedException e) {
         // interrupting this process is not supported.
         logger.warn(
             "This thread has been interrupted, but the interruption has "
                 + "been ignored to prevent loss of information.");
       }
     }
     if (isSagaOwner) {
       return !invocationDetected;
     }
     allVotesCast.signalAll();
   } finally {
     votingLock.unlock();
   }
   return false;
 }
 public void waitUntilNumIsAtLeast(int expected) {
   lock.lock();
   try {
     while (true) {
       if (num >= expected) return;
       log.fine(
           "Waiting "
               + uniqueId
               + ", expected sequence number "
               + expected
               + ", was "
               + num
               + ".");
       boolean timedOut = false;
       try {
         timedOut = !numIncreased.await(5, TimeUnit.SECONDS);
       } catch (InterruptedException e) {
         log.log(Level.FINE, "interrupted", e);
       }
       if (timedOut) {
         log.warning(
             uniqueId
                 + " expected sequence number "
                 + expected
                 + ", was "
                 + num
                 + ".  Continuing anyway");
         num++;
         numIncreased.signalAll();
       }
     }
   } finally {
     lock.unlock();
   }
 }
Example #5
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 TaskInfo getTaskToExecute(Spec<TaskInfo> criteria) {
    lock.lock();
    try {

      TaskInfo nextMatching;
      while ((nextMatching = getNextReadyAndMatching(criteria)) != null) {
        while (!nextMatching.allDependenciesComplete()) {
          try {
            condition.await();
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }

        // The task state could have been modified while we waited for dependency completion. Check
        // that it is still 'ready'.
        if (!nextMatching.isReady()) {
          continue;
        }

        if (nextMatching.allDependenciesSuccessful()) {
          nextMatching.startExecution();
          return nextMatching;
        } else {
          nextMatching.skipExecution();
          condition.signalAll();
        }
      }

      return null;

    } finally {
      lock.unlock();
    }
  }
  public Events<Event> get(Position start, int batchSize, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkUnGetSlotAt((LogPosition) start, batchSize)) {
          return doGet(start, batchSize);
        }

        if (nanos <= 0) {
          // 如果时间到了,有多少取多少
          return doGet(start, batchSize);
        }

        try {
          nanos = notEmpty.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notEmpty.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
 public static void escritorSeVa(Escritor escritor) {
   lock.lock();
   System.out.println("El Escritor:" + escritor.nombre + " Termino De Escribir.");
   escritorEscribiendo = false;
   if (!cola.isEmpty()) {
     if (cola.get(0).lector) {
       lectoresLeyendo = cola.get(0).cantidad;
       System.out.println("");
       System.out.println("Se setea lectoresLeyendo = " + lectoresLeyendo);
       System.out.println("");
       for (int i = 0; i < cola.get(0).cantidad; i++) {
         lectores.signal();
       }
       cola.remove(0);
     } else {
       cola.get(0).cantidad -= 1;
       escritorEscribiendo = true;
       if (cola.get(0).cantidad == 0) {
         cola.remove(0);
       }
       escritores.signal();
     }
   }
   lock.unlock();
 }
Example #9
0
  public T receive() {
    lock.lock();
    try {
      while (true) {
        DelayedMessage message = queue.peek();
        if (message == null && stopping) {
          return null;
        }
        if (message == null) {
          condition.await();
          continue;
        }

        long now = timeProvider.getCurrentTime();
        if (message.dispatchTime > now) {
          condition.awaitUntil(new Date(message.dispatchTime));
        } else {
          queue.poll();
          if (queue.isEmpty()) {
            condition.signalAll();
          }
          return message.message;
        }
      }
    } catch (InterruptedException e) {
      throw UncheckedException.throwAsUncheckedException(e);
    } finally {
      lock.unlock();
    }
  }
  public E take() throws InterruptedException {
    Node<E> x;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    try {
      try {
        while (count.get() == 0) notEmpty.await();
      } catch (InterruptedException ie) {
        notEmpty.signal(); // propagate to a non-interrupted thread
        throw ie;
      }

      x = extract();
      if (count.getAndDecrement() > 1) notEmpty.signal();
    } finally {
      takeLock.unlock();
    }

    E result = x.item;

    // temporary clearence
    x.item = null;
    x.next = null;

    return result;
  }
 public RunnableScheduledFuture<?> take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) available.await();
       else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
Example #12
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay > 0) {
           if (nanos <= 0) return null;
           if (delay > nanos) delay = nanos;
           long timeLeft = available.awaitNanos(delay);
           nanos -= delay - timeLeft;
         } else {
           E x = q.poll();
           assert x != null;
           if (q.size() != 0) available.signalAll();
           return x;
         }
       }
     }
   } finally {
     lock.unlock();
   }
 }
  void foo() {
    Object obj;
    Condition condition;
    synchronized (obj) {
      if (!suitableCondition()) {
        obj.wait(12); // Noncompliant {{Remove this call to "wait" or move it into a "while" loop.}}
        condition.await(); // Noncompliant
      }
      for (; ; ) {
        obj.wait(12);
      }
      do {
        obj.wait(12);
      } while (!suitableCondition);

      while (!suitableCondition()) {
        obj.wait(12);
        condition.await();
        while (!suitableCondition()) {
          obj.wait(12);
          condition.await();
        }
        obj.wait(12);
      }
    }
  }
  public void waitForLSPaddition(long lspId, long timeWait) {
    Lock lock;
    Condition lspEstablished;
    try {
      lock = lockList.get(lspId);
      if (lock == null) log.info("Lock is NULL!");
      lspEstablished = conditionList.get(lspId);
    } catch (Exception e) {
      return;
    }

    lock.lock();
    try {
      if (established == false) {
        log.info("Waiting " + timeWait + " ms  for LSP " + lspId + " to be established");
        lspEstablished.await(timeWait, TimeUnit.MILLISECONDS);
      } else {
        log.info("Inside waitForLSPaddition lockList.remove");
        // FIXME: Revisar esto
        lockList.remove(lspId);
        conditionList.remove(lspId);
      }
      log.info("LSP " + lspId + " has been established");
    } catch (InterruptedException e) {
      return;
    } finally {
      lock.unlock();
    }
  }
Example #15
0
  @Override
  public float[] getBlock(int timeout) {
    // TODO Auto-generated method stub
    float[] frame = null;
    lock.lock();
    try {

      if (listFrame.size() > 0) {
        frame = listFrame.removeFirst();
      }
      if (frame == null && timeout != 0) {
        try {
          if (timeout > 0) {

            condition.await(timeout, TimeUnit.MILLISECONDS);

          } else {
            condition.await();
          }
        } catch (InterruptedException e) {
          // TODO: handle exception
        }
      }
      if (listFrame.size() > 0) {
        frame = listFrame.removeFirst();
      }
    } finally {
      lock.unlock();
    }
    return frame;
  }
Example #16
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue.
  *
  * @return the head of this queue
  * @throws InterruptedException {@inheritDoc}
  */
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) available.await();
       else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay <= 0) return q.poll();
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
Example #17
0
  /**
   * Calls shutdown on current state and waits until a finished state is reached.
   *
   * @throws InterruptedException if the waiting for a finished state is interrupted.
   */
  public void shutdown() throws InterruptedException {
    stateLock.lock();
    try {
      isShutdown = true;

      // interrupts any take operations
      takeCallLock.lock();
      try {
        takeCallCondition.signalAll();
      } finally {
        takeCallLock.unlock();
      }

      currentServerState.shutdown();
      while (true) {
        if (currentServerState.getCurrentState() == ServerStates.Finished) {
          break;
        }
        if (currentServerState.getCurrentState() == ServerStates.Error) {
          break;
        }
        stateChangeCondition.await();
      }
      callMapCleanupTimer.cancel();
      callMapCleanupTask.cancel();
      stateTimeoutTimer.cancel();
    } catch (InterruptedException e) {
      throw e;
    } finally {
      stateLock.unlock();
    }
  }
Example #18
0
  /*
   * (non-Javadoc)
   *
   * @see java.io.Reader#read(char[], int, int)
   */
  @Override
  public int read(char[] cbuf, int off, int len) throws IOException {
    lock.lock(); // lock this object
    int i = 0;

    try {
      // while no data to read, place thread in waiting state
      while (size == 0) {
        if (blocking) notEmpty.await(); // await until a buffer element is
        // filled
        else {
          lock.unlock();
          return -1;
        }
      } // end while
    } // end try
    // if waiting thread interrupted, print stack trace
    catch (Exception exception) {
      exception.printStackTrace();
    } // end catch

    for (; i < len && i < size; i++) {
      cbuf[off + i] = (char) getByte();
    }
    notFull.signal();
    lock.unlock(); // unlock this object

    return i;
  }
  @Test(timeout = 1500l)
  public void testConditionWaitsForSignalOtherThread() throws Exception {
    final Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    final Condition firstCondition = firstLock.newCondition();

    firstLock.lock();
    // fire off a thread that will signal the main process thread
    testService.submit(
        new Runnable() {
          @Override
          public void run() {
            firstLock.lock();
            System.out.println("Lock acquired on second thread");
            try {
              firstCondition.signal();
              System.out.println("Lock signalled on second thread");
            } finally {
              System.out.println("Lock released on second thread");
              firstLock.unlock();
            }
          }
        });

    // wait for signal notification
    System.out.println("First thread waiting for notification");
    firstCondition.await();
    System.out.println("First thread has been notified");
  }
Example #20
0
  /**
   * Get bytes from the buffer and return these in an array. Blocks if the buffer is empty and no
   * values have yet been added to the array.
   *
   * @param buf array to return bytes
   * @param off the off
   * @param len the len
   * @return the number of bytes returned in the array
   */
  public int get(byte[] buf, int off, int len) {
    lock.lock(); // lock this object
    int i = 0;

    try {
      // while no data to read, place thread in waiting state
      while (size == 0) {
        // System.out.println("read wait");
        notEmpty.await(); // await until a buffer element is
        // filled
      } // end while
    } // end try
    // if waiting thread interrupted, print stack trace
    catch (Exception exception) {
      exception.printStackTrace();
    } // end catch

    for (; i < len && i < size; i++) {
      buf[off + i] = getByte();
    }
    notFull.signal();
    lock.unlock(); // unlock this object

    return i;
  }
Example #21
0
  /**
   * Get next value from the buffer. Blocks indefinitely if buffer is empty.
   *
   * @return the byte
   */
  public byte get() {
    byte result = 0; // initialize value read from buffer
    lock.lock(); // lock this object

    // wait until buffer has data, then read value
    try {
      // while no data to read, place thread in waiting state
      while (size == 0) {
        if (blocking) notEmpty.await(); // await until a buffer element is
        // filled
        else {
          lock.unlock();
          return 0;
        }
      } // end while

      result = getByte();
      notFull.signal();
    } // end try
    // if waiting thread interrupted, print stack trace
    catch (InterruptedException exception) {
      exception.printStackTrace();
      Thread.currentThread().interrupt();
    } // end catch
    finally {
      lock.unlock(); // unlock this object
    } // end finally

    return result;
  } // end method get
  public boolean put(List<Event> data, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    if (data == null || data.isEmpty()) {
      return true;
    }

    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkFreeSlotAt(putSequence.get() + data.size())) {
          doPut(data);
          return true;
        }
        if (nanos <= 0) {
          return false;
        }

        try {
          nanos = notFull.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notFull.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
Example #23
0
  public Session take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      while (active) {
        Session first = queue.peek();
        if (first == null) {
          available.await();
        } else {
          long delay = getDelay(first, TimeUnit.NANOSECONDS);
          if (delay > 0) {
            available.awaitNanos(delay);
          } else {
            Session x = queue.poll();
            assert x != null;
            if (queue.size() != 0) {
              available.signalAll(); // wake up other takers
            }
            return x;
          }
        }
      }

      throw new InterruptedException("Session queue is stopping");
    } finally {
      lock.unlock();
    }
  }
Example #24
0
 // Do not take any clustered write lock in this path.
 public void add(final E item) {
   if (null == item) return;
   int maxQueueSize = config.getMaxQueueSize();
   bucketWriteLock.lock();
   boolean interrupted = false;
   try {
     if (maxQueueSize != UNLIMITED_QUEUE_SIZE) {
       while (!isCancelled() && toolkitList.size() >= maxQueueSize) {
         try {
           bucketNotFull.await();
         } catch (final InterruptedException e) {
           interrupted = true;
         }
       }
     }
     boolean signalNotEmpty = toolkitList.isEmpty();
     toolkitList.unlockedAdd(item);
     if (signalNotEmpty) {
       bucketNotEmpty.signalAll();
     }
   } finally {
     bucketWriteLock.unlock();
     if (interrupted) {
       Thread.currentThread().interrupt();
     }
   }
 }
 public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
     throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
Example #26
0
  /**
   * Blocks until an object is received that is handled by process, or the specified timeout has
   * passed.
   *
   * <p>Once closed any attempt to wait will throw an exception.
   *
   * @param timeout The timeout in milliseconds.
   * @return The object that resolved the blocking.
   * @throws QpidException
   * @throws FailoverException
   */
  public Object block(long timeout) throws QpidException, FailoverException {
    if (timeout < 0) {
      throw new IllegalArgumentException("timeout must be zero or greater");
    }

    long nanoTimeout = TimeUnit.MILLISECONDS.toNanos(timeout);

    _lock.lock();

    try {
      if (_closed) {
        throw throwClosedException();
      }

      if (_error == null) {
        _waiting.set(true);

        while (!_ready && _error == null) {
          try {
            nanoTimeout = _receivedCondition.awaitNanos(nanoTimeout);

            if (nanoTimeout <= 0 && !_ready && _error == null) {
              _error = new AMQTimeoutException("Server did not respond in a timely fashion", null);
              _ready = true;
            }
          } catch (InterruptedException e) {
            _logger.error(e.getMessage(), e);
            // IGNORE    -- //fixme this isn't ideal as being interrupted isn't equivalent to
            // success
          }
        }
      }

      if (_error != null) {
        if (_error instanceof QpidException) {
          throw (QpidException) _error;
        } else if (_error instanceof FailoverException) {
          // This should ensure that FailoverException is not wrapped and can be caught.
          throw (FailoverException) _error; // needed to expose FailoverException.
        } else {
          throw new QpidException("Woken up due to " + _error.getClass(), _error);
        }
      }

    } finally {
      _waiting.set(false);

      // Release Error handling thread
      if (_error != null) {
        _errorAck = true;
        _errorConditionAck.signal();

        _error = null;
      }
      _lock.unlock();
    }

    return _doneObject;
  }
Example #27
0
 /*
  * (non-Javadoc)
  *
  * @see java.io.Reader#close()
  */
 public void close() {
   lock.lock();
   notFull.signal();
   notEmpty.signal();
   size = 0;
   putIndex = 0;
   getIndex = 0;
   lock.unlock();
 }
  @Test(timeout = 1000l)
  public void testConditionTimesOut() throws Exception {
    Lock firstLock = new ReentrantZkLock(baseLockPath, zkSessionManager);
    Condition firstCondition = firstLock.newCondition();

    firstLock.lock();
    boolean timedOut = firstCondition.await(250l, TimeUnit.MILLISECONDS);
    assertTrue("Condition did not time out!", !timedOut);
    firstLock.unlock();
  }
    // we don't care about the return value but care about it throwing exception
    public void runMayThrow() throws Exception {
      if (endpoints.isEmpty()) {
        differencingDone.signalAll();
        logger.info(
            "No neighbors to repair with for "
                + tablename
                + " on "
                + range
                + ": "
                + getName()
                + " completed.");
        return;
      }

      // Checking all nodes are live
      for (InetAddress endpoint : endpoints) {
        if (!FailureDetector.instance.isAlive(endpoint)) {
          differencingDone.signalAll();
          logger.info(
              "Could not proceed on repair because a neighbor ("
                  + endpoint
                  + ") is dead: "
                  + getName()
                  + " failed.");
          return;
        }
      }

      AntiEntropyService.instance.sessions.put(getName(), this);
      Gossiper.instance.register(this);
      FailureDetector.instance.registerFailureDetectionEventListener(this);
      try {
        // Create and queue a RepairJob for each column family
        for (String cfname : cfnames) {
          RepairJob job = new RepairJob(cfname);
          jobs.offer(job);
          activeJobs.put(cfname, job);
        }

        jobs.peek().sendTreeRequests();

        // block whatever thread started this session until all requests have been returned:
        // if this thread dies, the session will still complete in the background
        completed.await();
        if (exception != null) throw exception;
      } catch (InterruptedException e) {
        throw new RuntimeException(
            "Interrupted while waiting for repair: repair will continue in the background.");
      } finally {
        FailureDetector.instance.unregisterFailureDetectionEventListener(this);
        Gossiper.instance.unregister(this);
        AntiEntropyService.instance.sessions.remove(getName());
      }
    }
Example #30
0
 public void stopNow() {
   bucketWriteLock.lock();
   try {
     destroyAfterStop = false;
     stopState = STOP_STATE.STOPPED;
     bucketNotEmpty.signalAll();
     bucketNotFull.signalAll();
     processingWorkerThread.interrupt();
   } finally {
     bucketWriteLock.unlock();
   }
 }