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

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

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

Semaphore.release介绍

[英]Releases a permit, returning it to the semaphore.

Releases a permit, increasing the number of available permits by one. If any threads are trying to acquire a permit, then one is selected and given the permit that was just released. That thread is (re)enabled for thread scheduling purposes.

There is no requirement that a thread that releases a permit must have acquired that permit by calling #acquire. Correct usage of a semaphore is established by programming convention in the application.
[中]释放许可证,并将其返回到信号灯。
释放许可证,将可用许可证的数量增加一个。如果有任何线程试图获得许可,那么就会选择一个线程,并给予刚刚发布的许可。出于线程调度的目的,该线程已(重新)启用。
不要求发布许可证的线程必须通过调用#acquire获得该许可证。信号量的正确使用由应用程序中的编程约定确定。

代码示例

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

@Override
  public void run() {
    try {
      toRun.sem.acquire();
      toRun.runInOrder();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      toRun.sem.release();
      gateway.release();
    }
  }
}

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

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  if (unit == null) {
    throw new NullPointerException("unit");
  }
  if (inEventLoop()) {
    throw new IllegalStateException("cannot await termination of the current thread");
  }
  if (threadLock.tryAcquire(timeout, unit)) {
    threadLock.release();
  }
  return isTerminated();
}

代码示例来源:origin: Red5/red5-server

/** {@inheritDoc} */
@Override
public boolean start(IScope scope) {
  if (lock == null) {
    lock = new Semaphore(1, true);
  }
  try {
    lock.tryAcquire(1, TimeUnit.SECONDS);
    return super.start(scope);
  } catch (InterruptedException e) {
    e.printStackTrace();
  } finally {
    lock.release();
  }
  return false;
}

代码示例来源:origin: stackoverflow.com

public class BoundedExecutor {
  private final Executor exec;
  private final Semaphore semaphore;

  public BoundedExecutor(Executor exec, int bound) {
    this.exec = exec;
    this.semaphore = new Semaphore(bound);
  }

  public void submitTask(final Runnable command)
      throws InterruptedException, RejectedExecutionException {
    semaphore.acquire();
    try {
      exec.execute(new Runnable() {
        public void run() {
          try {
            command.run();
          } finally {
            semaphore.release();
          }
        }
      });
    } catch (RejectedExecutionException e) {
      semaphore.release();
      throw e;
    }
  }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException {
 BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
 ExecutorService service = Executors.newSingleThreadExecutor();
 try {
  PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1);
  final Semaphore jobSemaphore = new Semaphore(0);
  final Semaphore testSemaphore = new Semaphore(0);
  final AtomicBoolean interrupted = new AtomicBoolean();
  executor.submit(() -> {
   testSemaphore.release();
   try {
    jobSemaphore.acquire();
   } catch (InterruptedException e) {
    interrupted.set(true);
   }
  });
  testSemaphore.acquireUninterruptibly();
  assertThat(executor.shutdownNow(), empty());
  assertThat(executor.awaitTermination(2, MINUTES), is(true));
  assertThat(executor.isShutdown(), is(true));
  assertThat(executor.isTerminated(), is(true));
  assertThat(jobSemaphore.availablePermits(), is(0));
  assertThat(interrupted.get(), is(true));
 } finally {
  service.shutdown();
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testFaultsDoNotGetToEvictionAdvisor() throws StoreAccessException {
 final Semaphore semaphore = new Semaphore(0);
 final OnHeapStoreForTests<String, String> store = newStore(SystemTimeSource.INSTANCE, noAdvice());
 ExecutorService executor = Executors.newCachedThreadPool();
 try {
  executor.submit(() -> store.getOrComputeIfAbsent("prime", key -> {
   semaphore.acquireUninterruptibly();
   return new OnHeapValueHolder<String>(0, 0, false) {
    @Override
    public String get() {
     return key;
    }
   };
  }));
  while (!semaphore.hasQueuedThreads());
  store.put("boom", "boom");
 } finally {
  semaphore.release(1);
  executor.shutdown();
 }
}

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

@Test
public void eachRequestThreadEnvironmentIsConfinedToItsThread() {
 Semaphore thread1Permit = new Semaphore(0);
 Semaphore thread2Permit = new Semaphore(0);
 Callable<Void> request1Task = () -> processRequest("thread 1", thread1Permit, thread2Permit);
 Callable<Void> request2Task = () -> processRequest("thread 2", thread2Permit, thread1Permit);
 runConcurrently.setTimeout(Duration.ofMinutes(1));
 runConcurrently.add(request1Task);
 runConcurrently.add(request2Task);
 thread1Permit.release();
 runConcurrently.executeInParallel();
}

代码示例来源:origin: appium/java-client

@Test
  public void verifyLogcatListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addLogcatMessagesListener((msg) -> messageSemaphore.release());
    driver.addLogcatConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addLogcatDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addLogcatErrorsListener(Throwable::printStackTrace);
    try {
      driver.startLogcatBroadcast();
      messageSemaphore.acquire();
      // This is needed for pushing some internal log messages
      driver.runAppInBackground(Duration.ofSeconds(1));
      assertTrue(String.format("Didn't receive any log message after %s timeout",
          DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
          messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    } finally {
      messageSemaphore.release();
      driver.stopLogcatBroadcast();
    }
  }
}

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

/**
 *
 */
private void acquireRemapSemaphore() throws IgniteInterruptedCheckedException {
  try {
    if (remapSem.availablePermits() != REMAP_SEMAPHORE_PERMISSIONS_COUNT) {
      if (timeout == DFLT_UNLIMIT_TIMEOUT) {
        // Wait until failed data being processed.
        remapSem.acquire(REMAP_SEMAPHORE_PERMISSIONS_COUNT);
        remapSem.release(REMAP_SEMAPHORE_PERMISSIONS_COUNT);
      }
      else {
        // Wait until failed data being processed.
        boolean res = remapSem.tryAcquire(REMAP_SEMAPHORE_PERMISSIONS_COUNT, timeout, TimeUnit.MILLISECONDS);
        if (res)
          remapSem.release(REMAP_SEMAPHORE_PERMISSIONS_COUNT);
        else
          throw new IgniteDataStreamerTimeoutException("Data streamer exceeded timeout " +
            "while was waiting for failed data resending finished.");
      }
    }
  }
  catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new IgniteInterruptedCheckedException(e);
  }
}

代码示例来源:origin: stackoverflow.com

private static Semaphore semaphore = new Semaphore(1024 * 1024, true);
  semaphore.acquire(size);
  semaphore.release(array.length);

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

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
 if (readerSemaphore.tryAcquire(time, unit)) {
  int oldNumReaders = numReaders;
  numReaders++;
  if (numReaders == 1) {
   if (writerSemaphore.tryAcquire(time, unit)) {
    readerSemaphore.release();
    return true;
   } else {
    numReaders = oldNumReaders;
    readerSemaphore.release();
    return false;
   }
  } else {
   readerSemaphore.release();
   return true;
  }
 }
 return false;
}

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

public void addCall(final FSTRunnable toRun) throws InterruptedException {
  gateway.acquire();
  if (jobs[curIdx] == null) {
    jobs[curIdx] = toRun;
  } else {
    jobs[curIdx].sem.acquire();
    jobs[curIdx].sem.release();
    jobs[curIdx] = toRun;
  }
  toRun.sem = sems[curIdx];
  toRun.sem.acquire();
  OrderedRunnable ord = orderedRunnableCache[curIdx];
  ord.toRun = toRun;
  curIdx = (curIdx + 1) % threads;
  orderedPool.execute(ord);
  pool.execute(toRun);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testRunningJobIsInterruptedAfterShutdownNow() throws InterruptedException {
 BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
 ExecutorService service = Executors.newSingleThreadExecutor();
 try {
  PartitionedOrderedExecutor executor = new PartitionedOrderedExecutor(queue, service);
  final Semaphore jobSemaphore = new Semaphore(0);
  final Semaphore testSemaphore = new Semaphore(0);
  final AtomicBoolean interrupted = new AtomicBoolean();
  executor.submit(() -> {
   testSemaphore.release();
   try {
    jobSemaphore.acquire();
   } catch (InterruptedException e) {
    interrupted.set(true);
   }
  });
  testSemaphore.acquireUninterruptibly();
  assertThat(executor.shutdownNow(), empty());
  assertThat(executor.awaitTermination(2, MINUTES), is(true));
  assertThat(executor.isShutdown(), is(true));
  assertThat(executor.isTerminated(), is(true));
  assertThat(jobSemaphore.availablePermits(), is(0));
  assertThat(interrupted.get(), is(true));
 } finally {
  service.shutdown();
 }
}

代码示例来源:origin: LeonardoZ/java-concurrency-patterns

public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();
    Semaphore semaphore = new Semaphore(3);

    Runnable r = () -> {
      try {
        System.out.println("Trying to acquire - " + Thread.currentThread().getName());
        if (semaphore.tryAcquire(2, TimeUnit.SECONDS)) {
          // use-get resource
          // simulate work in progress
          System.out.println("Acquired - " + Thread.currentThread().getName());
          Thread.sleep(2000);
          System.out.println("Done - " + Thread.currentThread().getName());
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        semaphore.release();
      }
    };
    for (int i = 0; i < 4; i++) {
      executor.execute(r);
    }
    
    executor.shutdown();

  }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testQueuedJobIsStoppedAfterShutdownNow() throws InterruptedException {
 BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
 ExecutorService service = Executors.newSingleThreadExecutor();
 try {
  PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1);
  final Semaphore jobSemaphore = new Semaphore(0);
  final Semaphore testSemaphore = new Semaphore(0);
  executor.submit(() -> {
   testSemaphore.release();
   jobSemaphore.acquireUninterruptibly();
  });
  final AtomicBoolean called = new AtomicBoolean();
  executor.submit(() -> called.set(true));
  testSemaphore.acquireUninterruptibly();
  assertThat(executor.shutdownNow(), hasSize(1));
  assertThat(executor.awaitTermination(100, MILLISECONDS), is(false));
  assertThat(executor.isShutdown(), is(true));
  assertThat(executor.isTerminated(), is(false));
  jobSemaphore.release();
  assertThat(executor.awaitTermination(2, MINUTES), is(true));
  assertThat(executor.isShutdown(), is(true));
  assertThat(executor.isTerminated(), is(true));
  assertThat(jobSemaphore.availablePermits(), is(0));
  assertThat(called.get(), is(false));
 } finally {
  service.shutdown();
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testShutdownButNonTerminatedExecutorRejectsJob() throws InterruptedException {
 BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
 ExecutorService service = Executors.newSingleThreadExecutor();
 try {
  PartitionedUnorderedExecutor executor = new PartitionedUnorderedExecutor(queue, service, 1);
  final Semaphore semaphore = new Semaphore(0);
  executor.execute(semaphore::acquireUninterruptibly);
  executor.shutdown();
  try {
   executor.execute(() -> {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
   });
   fail("Expected RejectedExecutionException");
  } catch (RejectedExecutionException e) {
   //expected
  }
  semaphore.release();
  assertThat(executor.awaitTermination(2, MINUTES), is(true));
 } finally {
  service.shutdown();
 }
}

代码示例来源:origin: appium/java-client

@Test
  public void verifySyslogListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addSyslogMessagesListener((msg) -> messageSemaphore.release());
    driver.addSyslogConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addSyslogDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addSyslogErrorsListener(Throwable::printStackTrace);
    try {
      driver.startSyslogBroadcast();
      messageSemaphore.acquire();
      // This is needed for pushing some internal log messages
      driver.runAppInBackground(Duration.ofSeconds(1));
      assertTrue(String.format("Didn't receive any log message after %s timeout",
          DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
          messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    } finally {
      messageSemaphore.release();
      driver.stopSyslogBroadcast();
    }
  }
}

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

case 0:
  LOG.info("First peer, do nothing, just join");
  if(finish0.tryAcquire(1000, java.util.concurrent.TimeUnit.MILLISECONDS)){
  LOG.info("Second entering case");
  if(round[1] != 0){
    finish0.release();
    flag = false;
  } else {
    finish3.acquire();
    start0.release();
  flag = false;
  round[2] = 1;
  finish3.release();
  LOG.info("Third leaving");
  break;

代码示例来源:origin: jenkinsci/jenkins

mutexByTool.put(tool, semaphore = new Semaphore(1));
semaphore.acquire();
try {
  return installer.performInstallation(tool, node, log).getRemote();
} finally {
  semaphore.release();

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

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  if (unit == null) {
    throw new NullPointerException("unit");
  }
  if (inEventLoop()) {
    throw new IllegalStateException("cannot await termination of the current thread");
  }
  if (threadLock.tryAcquire(timeout, unit)) {
    threadLock.release();
  }
  return isTerminated();
}

相关文章