java.util.concurrent.Semaphore.drainPermits()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(6.6k)|赞(0)|评价(0)|浏览(163)

本文整理了Java中java.util.concurrent.Semaphore.drainPermits()方法的一些代码示例,展示了Semaphore.drainPermits()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Semaphore.drainPermits()方法的具体详情如下:
包路径:java.util.concurrent.Semaphore
类名称:Semaphore
方法名:drainPermits

Semaphore.drainPermits介绍

[英]Acquires and returns all permits that are immediately available.
[中]

代码示例

代码示例来源:origin: wildfly/wildfly

@Override
public synchronized void releaseOutstanding() {
 semaphore.drainPermits();
}

代码示例来源:origin: wildfly/wildfly

@Override
public synchronized void reset() {
 // Any pendingCredits credits from before failover won't arrive, so we re-initialise
 semaphore.drainPermits();
 super.reset();
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

/**
 * drainTo defers to each sub-queue. Note that draining from a FairCallQueue
 * to another FairCallQueue will likely fail, since the incoming calls
 * may be scheduled differently in the new FairCallQueue. Nonetheless this
 * method is provided for completeness.
 */
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
 // initially take all permits to stop consumers from modifying queues
 // while draining.  will restore any excess when done draining.
 final int permits = semaphore.drainPermits();
 final int numElements = Math.min(maxElements, permits);
 int numRemaining = numElements;
 for (int i=0; numRemaining > 0 && i < queues.size(); i++) {
  numRemaining -= queues.get(i).drainTo(c, numRemaining);
 }
 int drained = numElements - numRemaining;
 if (permits > drained) { // restore unused permits.
  semaphore.release(permits - drained);
 }
 return drained;
}

代码示例来源:origin: apache/flume

@Override
void beginCheckpoint() throws IOException {
 LOG.info("Start checkpoint for " + checkpointFile +
   ", elements to sync = " + overwriteMap.size());
 if (shouldBackup) {
  int permits = backupCompletedSema.drainPermits();
  Preconditions.checkState(permits <= 1, "Expected only one or less " +
    "permits to checkpoint, but got " + String.valueOf(permits) +
    " permits");
  if (permits < 1) {
   // Force the checkpoint to not happen by throwing an exception.
   throw new IOException("Previous backup of checkpoint files is still " +
     "in progress. Will attempt to checkpoint only at the end of the " +
     "next checkpoint interval. Try increasing the checkpoint interval " +
     "if this error happens often.");
  }
 }
 // Start checkpoint
 elementsBuffer.put(INDEX_CHECKPOINT_MARKER, CHECKPOINT_INCOMPLETE);
 mappedBuffer.force();
}

代码示例来源:origin: apache/zookeeper

waitSasl.drainPermits();
needSasl.set(true);
sendPrimePacket();

代码示例来源:origin: spotify/helios

semaphore.drainPermits();

代码示例来源:origin: lealone/Lealone

@Override
  public void run() {
    while (!isClosed) {
      try {
        semaphore.tryAcquire(loopInterval, TimeUnit.MILLISECONDS);
        semaphore.drainPermits();
      } catch (InterruptedException e) {
        throw new AssertionError();
      }
      try {
        checkpoint(false);
      } catch (Exception e) {
        logger.error("Failed to execute checkpoint", e);
      }
    }
  }
}

代码示例来源:origin: neo4j/neo4j

@AfterEach
private void refillSemaphore()
{
  // This ensures that no threads end up stuck
  semaphore.drainPermits();
  semaphore.release( Integer.MAX_VALUE );
}

代码示例来源:origin: apache/ignite

/**
 * @param hdr Queue header.
 */
public void onHeaderChanged(GridCacheQueueHeader hdr) {
  if (!hdr.empty()) {
    readSem.drainPermits();
    readSem.release(hdr.size());
  }
  if (bounded()) {
    writeSem.drainPermits();
    if (!hdr.full())
      writeSem.release(hdr.capacity() - hdr.size());
  }
}

代码示例来源:origin: apache/flume

int availablePermits = backupCompletedSema.drainPermits();
Preconditions.checkState(availablePermits == 0,
  "Expected no permits to be available in the backup semaphore, " +

代码示例来源:origin: apache/activemq

this.globalQueueSemaphore.drainPermits();
this.globalTopicSemaphore.drainPermits();

代码示例来源:origin: lealone/Lealone

@Override
public void run() {
  while (running) {
    long syncStarted = System.currentTimeMillis();
    sync();
    lastSyncedAt = syncStarted;
    syncComplete.signalAll();
    long now = System.currentTimeMillis();
    long sleep = syncStarted + syncIntervalMillis - now;
    if (sleep < 0)
      continue;
    try {
      haveWork.tryAcquire(sleep, TimeUnit.MILLISECONDS);
      haveWork.drainPermits();
    } catch (InterruptedException e) {
      throw new AssertionError();
    }
  }
  // 结束前最后sync一次
  sync();
  // 放在最后,让线程退出后再关闭
  redoLog.close();
}

代码示例来源:origin: Graylog2/graylog2-server

journalFilled.drainPermits();
} else {
  readMessages.mark(encodedRawMessages.size());

代码示例来源:origin: wildfly/wildfly

@Override
protected void afterAcquired(int credits) throws ActiveMQAddressFullException {
 // check to see if the blocking mode is FAIL on the server
 synchronized (this) {
   super.afterAcquired(credits);
   if (serverRespondedWithFail) {
    serverRespondedWithFail = false;
    // remove existing credits to force the client to ask the server for more on the next send
    semaphore.drainPermits();
    pendingCredits = 0;
    arriving = 0;
    throw ActiveMQClientMessageBundle.BUNDLE.addressIsFull(address.toString(), credits);
   }
 }
}

代码示例来源:origin: lealone/Lealone

@Override
public void executeNextStatement() {
  int priority = PreparedStatement.MIN_PRIORITY;
  while (true) {
    PreparedCommand c = getNextBestCommand(priority, true);
    if (c == null) {
      try {
        haveWork.tryAcquire(loopInterval, TimeUnit.MILLISECONDS);
        haveWork.drainPermits();
      } catch (InterruptedException e) {
        throw new AssertionError();
      }
      break;
    }
    try {
      c.execute();
    } catch (Throwable e) {
      c.transfer.getTransferConnection().sendError(c.transfer, c.id, e);
    }
  }
}

代码示例来源:origin: googleapis/google-cloud-java

@Before
public void before() {
 requests.clear();
 documentSnapshots.clear();
 exceptions.clear();
 querySnapshots.clear();
 closes.drainPermits();
 lastSnapshot = null;
 doReturn(immediateExecutor).when(firestoreRpc).getExecutor();
 doAnswer(newRequestObserver())
   .when(firestoreMock)
   .streamRequest(streamObserverCapture.capture(), Matchers.<BidiStreamingCallable>any());
}

代码示例来源:origin: neo4j/neo4j

private Future<Void> makeWorkStuckAtSemaphore( int delta )
{
  semaphore.drainPermits();
  Future<Void> concurrentWork = executor.submit( new CallableWork( new AddWork( delta ) ) );
  assertThrows( TimeoutException.class, () -> concurrentWork.get( 10, TimeUnit.MILLISECONDS ) );
  while ( !semaphore.hasQueuedThreads() )
  {
    usleep( 1 );
  }
  // good, the concurrent AddWork is now stuck on the semaphore
  return concurrentWork;
}

代码示例来源:origin: neo4j/neo4j

@Test
public void mustNotRescheduleRecurringTasksThatThrows() throws Exception
{
  Runnable runnable = () ->
  {
    semaphore.release();
    throw new RuntimeException( "boom" );
  };
  JobHandle handle = scheduler.submit( Group.STORAGE_MAINTENANCE, runnable, 100, 100 );
  clock.forward( 100, TimeUnit.NANOSECONDS );
  scheduler.tick();
  assertSemaphoreAcquire();
  clock.forward( 100, TimeUnit.NANOSECONDS );
  scheduler.tick();
  try
  {
    handle.waitTermination();
    fail( "waitTermination should have thrown because the task should have failed." );
  }
  catch ( ExecutionException e )
  {
    assertThat( e.getCause().getMessage(), is( "boom" ) );
  }
  assertThat( semaphore.drainPermits(), is( 0 ) );
}

代码示例来源:origin: neo4j/neo4j

semaphore.drainPermits();

代码示例来源:origin: org.apache.hadoop/hadoop-hdfs

@Override
public int drainPermits() {
 draining.set(true);
 return super.drainPermits();
}
// while draining, count the releases until release(int)

相关文章