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
   }
 }
    // 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());
      }
    }
示例#3
0
 public void stopNow() {
   bucketWriteLock.lock();
   try {
     destroyAfterStop = false;
     stopState = STOP_STATE.STOPPED;
     bucketNotEmpty.signalAll();
     bucketNotFull.signalAll();
     processingWorkerThread.interrupt();
   } finally {
     bucketWriteLock.unlock();
   }
 }
示例#4
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();
    }
  }
 /**
  * @throws UnsupportedOperationException {@inheritDoc}
  * @throws ClassCastException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  * @throws IllegalArgumentException {@inheritDoc}
  */
 public int drainTo(Collection<? super E> c, int maxElements) {
   if (c == null) throw new NullPointerException();
   if (c == this) throw new IllegalArgumentException();
   if (maxElements <= 0) return 0;
   final E[] items = this.items;
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     int i = takeIndex;
     int n = 0;
     int sz = count;
     int max = (maxElements < count) ? maxElements : count;
     while (n < max) {
       c.add(items[i]);
       items[i] = null;
       i = inc(i);
       ++n;
     }
     if (n > 0) {
       count -= n;
       takeIndex = i;
       notFull.signalAll();
     }
     return n;
   } finally {
     lock.unlock();
   }
 }
示例#6
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;
 }
示例#8
0
  /**
   * Removes the next element (at hd +1). <em>Note that this method is not concurrent, as RingBuffer
   * can only have 1 remover thread active at any time !</em>
   *
   * @param nullify Nulls the element in the array if true
   * @return T if there was a non-null element at position hd +1, or null if the element at hd+1 was
   *     null, or hd+1 > hr.
   */
  public T remove(boolean nullify) {
    long tmp = hd + 1;
    if (tmp > hr.get()) return null;
    int index = index(tmp);
    T element = buf.get(index);
    if (element == null) return null;
    hd = tmp;

    if (nullify) {
      long tmp_low = low;
      if (tmp == tmp_low + 1) buf.compareAndSet(index, element, null);
      else {
        int from = index(tmp_low + 1), length = (int) (tmp - tmp_low), capacity = capacity();
        for (int i = from; i < from + length; i++) {
          index = i % capacity;
          buf.set(index, null);
        }
      }
      low = tmp;
      lock.lock();
      try {
        buffer_full.signalAll();
      } finally {
        lock.unlock();
      }
    }
    return element;
  }
 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();
   }
 }
示例#10
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();
    }
  }
示例#11
0
  /**
   * Append next message part to the buffer.
   *
   * @param message the message.
   * @param last should be {@code true} iff this is the last part of the message, {@code false}
   *     otherwise.
   */
  public void appendMessagePart(ByteBuffer message, boolean last) {
    lock.lock();
    try {
      currentlyBuffered += message.remaining();
      if (currentlyBuffered <= bufferSize) {
        bufferedFragments.add(message);
      } else {
        final MessageTooBigException messageTooBigException =
            new MessageTooBigException(LocalizationMessages.PARTIAL_MESSAGE_BUFFER_OVERFLOW());
        LOGGER.log(
            Level.FINE,
            LocalizationMessages.PARTIAL_MESSAGE_BUFFER_OVERFLOW(),
            messageTooBigException);
        receivedLast = true;
        throw messageTooBigException;
      }

      this.receivedLast = last;
      condition.signalAll();
    } finally {
      lock.unlock();
    }

    if (this.inputStream == null) {
      this.inputStream = new BufferedInputStream(this);
      executorService.execute(
          new Runnable() {
            @Override
            public void run() {
              messageHandler.onMessage(inputStream);
            }
          });
    }
  }
示例#12
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();
    }
  }
示例#13
0
  protected void flush(final Address new_coord) throws InterruptedException {
    // wait until all threads currently sending messages have returned (new threads after
    // flushing=true) will block
    // flushing is set to true in startFlusher()
    while (flushing && running) {
      if (in_flight_sends.get() == 0) break;
      Thread.sleep(100);
    }

    send_lock.lockInterruptibly();
    try {
      if (log.isTraceEnabled())
        log.trace(local_addr + ": coord changed from " + coord + " to " + new_coord);
      coord = new_coord;
      is_coord = Objects.equals(local_addr, coord);
      flushMessagesInForwardTable();
    } finally {
      if (log.isTraceEnabled()) log.trace(local_addr + ": flushing completed");
      flushing = false;
      ack_mode = true; // go to ack-mode after flushing
      num_acks = 0;
      send_cond.signalAll();
      send_lock.unlock();
    }
  }
示例#14
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();
   }
 }
  private void onStartCommand(String commandDisplayName, Runnable onDisconnect) {
    lock.lock();
    try {
      switch (state) {
        case Broken:
          throw new DaemonUnavailableException("This daemon is in a broken state and will stop.");
        case StopRequested:
          throw new DaemonUnavailableException("This daemon is currently stopping.");
        case Stopped:
          throw new DaemonUnavailableException("This daemon has stopped.");
      }
      if (currentCommandExecution != null) {
        throw new DaemonUnavailableException(
            String.format("This daemon is currently executing: %s", currentCommandExecution));
      }

      LOGGER.debug(
          "onStartCommand({}) called after {} minutes of idle",
          commandDisplayName,
          getIdleMinutes());
      try {
        onStartCommand.run();
        currentCommandExecution = commandDisplayName;
        this.onDisconnect = onDisconnect;
        updateActivityTimestamp();
        condition.signalAll();
      } catch (Throwable throwable) {
        setState(State.Broken);
        throw UncheckedException.throwAsUncheckedException(throwable);
      }
    } finally {
      lock.unlock();
    }
  }
 private void onFinishCommand() {
   lock.lock();
   try {
     String execution = currentCommandExecution;
     LOGGER.debug("onFinishCommand() called while execution = {}", execution);
     currentCommandExecution = null;
     onDisconnect = null;
     updateActivityTimestamp();
     switch (state) {
       case Running:
         try {
           onFinishCommand.run();
           condition.signalAll();
         } catch (Throwable throwable) {
           setState(State.Broken);
           throw UncheckedException.throwAsUncheckedException(throwable);
         }
         break;
       case StopRequested:
         stop();
         break;
       case Stopped:
         break;
       default:
         throw new IllegalStateException("Daemon is in unexpected state: " + state);
     }
   } finally {
     lock.unlock();
   }
 }
示例#17
0
  private void backgroundCall() throws IOException {
    mutex.lock();
    try {
      if (backgroundCompaction == null) {
        return;
      }

      try {
        if (!shuttingDown.get()) {
          backgroundCompaction();
        }
      } finally {
        backgroundCompaction = null;
      }
    } finally {
      try {
        // Previous compaction may have produced too many files in a level,
        // so reschedule another compaction if needed.
        maybeScheduleCompaction();
      } finally {
        try {
          backgroundCondition.signalAll();
        } finally {
          mutex.unlock();
        }
      }
    }
  }
示例#18
0
  private void compactMemTableInternal() throws IOException {
    Preconditions.checkState(mutex.isHeldByCurrentThread());
    if (immutableMemTable == null) {
      return;
    }

    try {
      // Save the contents of the memtable as a new Table
      VersionEdit edit = new VersionEdit();
      Version base = versions.getCurrent();
      writeLevel0Table(immutableMemTable, edit, base);

      if (shuttingDown.get()) {
        throw new DatabaseShutdownException("Database shutdown during memtable compaction");
      }

      // Replace immutable memtable with the generated Table
      edit.setPreviousLogNumber(0);
      edit.setLogNumber(log.getFileNumber()); // Earlier logs no longer needed
      versions.logAndApply(edit);

      immutableMemTable = null;

      deleteObsoleteFiles();
    } finally {
      backgroundCondition.signalAll();
    }
  }
示例#19
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();
    }
  }
    @Override
    public void handleMessage(Message msg) {
      if (!mListenerAdded) {
        Looper.myQueue().addIdleHandler(this);
        mListenerAdded = true;
      }
      removeMessages(BLANK);

      lock.lock();
      try {

        // Perform up to 10 tasks at once.
        // Consider only performing 10 remove tasks, not adds and animations.
        // Removes are relatively slow and are much better when batched.
        for (int i = 0; i < 10; i++) {
          performNextTask();
        }

        if (!isBusy()) {
          mListenerAdded = false;
          Looper.myQueue().removeIdleHandler(this);
          // Signal any other threads that are waiting.
          busyCondition.signalAll();
        } else {
          // Sometimes the idle queue may not be called - schedule up some work regardless
          // of whether the UI thread is busy or not.
          // TODO: try to remove this.
          sendEmptyMessageDelayed(BLANK, 10);
        }
      } finally {
        lock.unlock();
      }
    }
示例#21
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 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 void doNotify() {
   lock.lock();
   try {
     condition.signalAll();
   } finally {
     lock.unlock();
   }
 }
示例#24
0
 private void signalStop() {
   bucketWriteLock.lock();
   try {
     stoppedButBucketNotEmpty.signalAll();
   } finally {
     bucketWriteLock.unlock();
   }
 }
 public void stop(int maxTime) {
   if (maxTime != 0) {
     awaitFinish(maxTime);
   }
   synchronized (this) {
     runState = STATE_STOP;
   }
   try {
     lock.lock();
     hasFreeThread.signalAll();
     hasTask.signalAll();
     releaseAllFreeThread();
   } finally {
     lock.unlock();
   }
   logger.info("线程池即将关闭");
 }
示例#26
0
 public void finishJoin() {
   joinStateLock.lock();
   try {
     joinState = JoinState.JOINED;
     joined.signalAll();
   } finally {
     joinStateLock.unlock();
   }
 }
 @Override
 public void signalAllWhenBlocking() {
   lock.lock();
   try {
     processorNotifyCondition.signalAll();
   } finally {
     lock.unlock();
   }
 }
示例#28
0
 public void stop() {
   bucketWriteLock.lock();
   try {
     workDelay.set(0);
     stopState = STOP_STATE.STOP_REQUESTED;
     while (!toolkitList.isEmpty()) {
       stoppedButBucketNotEmpty.await();
     }
     stopState = STOP_STATE.STOPPED;
     bucketNotEmpty.signalAll();
     bucketNotFull.signalAll();
     processingWorkerThread.interrupt();
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
   } finally {
     bucketWriteLock.unlock();
   }
 }
示例#29
0
  public void unlock() {
    lock.lock();

    failingOver = false;

    failoverCondition.signalAll();

    lock.unlock();
  }
示例#30
0
 /**
  * Queues error that will be thrown in any waiting thread or any thread that attempts to wait on
  * this future hereafter.
  *
  * @param e the error
  */
 public void error(Throwable e) {
   lock();
   try {
     pendingEx = chainer.chain(e);
     cond.signalAll();
   } finally {
     unlock();
   }
 }