本文整理了Java中java.util.concurrent.Semaphore.tryAcquire()
方法的一些代码示例,展示了Semaphore.tryAcquire()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Semaphore.tryAcquire()
方法的具体详情如下:
包路径:java.util.concurrent.Semaphore
类名称:Semaphore
方法名:tryAcquire
[英]Acquires a permit from this semaphore, only if one is available at the time of invocation.
Acquires a permit, if one is available and returns immediately, with the value true, reducing the number of available permits by one.
If no permit is available then this method will return immediately with the value false.
Even when this semaphore has been set to use a fair ordering policy, a call to tryAcquire() will immediately acquire a permit if one is available, whether or not other threads are currently waiting. This "barging" behavior can be useful in certain circumstances, even though it breaks fairness. If you want to honor the fairness setting, then use #tryAcquire(long,TimeUnit)which is almost equivalent (it also detects interruption).
[中]仅当调用时有一个信号量可用时,才从该信号量获取许可。
获取许可证(如果有)并立即返回,值为true,将可用许可证的数量减少一个。
如果没有可用的许可证,则此方法将立即返回值false。
即使将此信号量设置为使用公平排序策略,调用tryAcquire()也会立即获得许可证(如果有),无论其他线程当前是否正在等待。这种“讨价还价”行为在某些情况下是有用的,即使它破坏了公平性。如果你想遵守公平性设置,那么就使用#tryAcquire(long,TimeUnit),它几乎是等效的(它还检测到中断)。
代码示例来源: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: 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
@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 void leave(IClient client, IScope scope) {
try {
lock.tryAcquire(1, TimeUnit.SECONDS);
super.leave(client, scope);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
}
代码示例来源:origin: Red5/red5-server
/** {@inheritDoc} */
@Override
public void stop(IScope scope) {
try {
lock.tryAcquire(1, TimeUnit.SECONDS);
super.stop(scope);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
}
代码示例来源:origin: Red5/red5-server
/** {@inheritDoc} */
@Override
public void disconnect(IConnection conn, IScope scope) {
try {
lock.tryAcquire(1, TimeUnit.SECONDS);
super.disconnect(conn, scope);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
}
代码示例来源:origin: apache/incubator-dubbo
if (!guard.tryAcquire()) {
return;
logger.error("dump jStack error", t);
} finally {
guard.release();
代码示例来源:origin: apache/incubator-dubbo
if (!guard.tryAcquire()) {
return;
logger.error("dump jStack error", t);
} finally {
guard.release();
代码示例来源:origin: Red5/red5-server
/** {@inheritDoc} */
@Override
public boolean connect(IConnection conn, IScope scope, Object[] params) {
try {
lock.tryAcquire(1, TimeUnit.SECONDS);
return super.connect(conn, scope, params);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
return false;
}
代码示例来源:origin: Red5/red5-server
/** {@inheritDoc} */
@Override
public boolean join(IClient client, IScope scope) {
try {
lock.tryAcquire(1, TimeUnit.SECONDS);
return super.join(client, scope);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
return false;
}
代码示例来源: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: SonarSource/sonarqube
@Override
public void startIt() {
if (semaphore.tryAcquire()) {
try {
executorService.execute(this::doDatabaseMigration);
} catch (RuntimeException e) {
semaphore.release();
throw e;
}
} else {
LOGGER.trace("{}: lock is already taken or process is already running", Thread.currentThread().getName());
}
}
代码示例来源:origin: wildfly/wildfly
@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: apache/geode
/**
* Wait for any pending operations, and notify the the completions that the operations and done.
*/
@Override
public void waitForOperations() {
boolean interrupted = false;
while (!executor.isShutdown()) {
try {
if (operationSemaphore.tryAcquire(maxParallelOperations, 1, TimeUnit.SECONDS)) {
operationSemaphore.release(maxParallelOperations);
drainCompletions();
if (interrupted) {
Thread.currentThread().interrupt();
}
return;
}
} catch (InterruptedException e) {
interrupted = true;
}
}
}
代码示例来源: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
@Override
public void run() {
try {
liveThreads.add(Thread.currentThread());
try {
queue.remove().run();
} finally {
liveThreads.remove(Thread.currentThread());
}
} finally {
if (queue.isEmpty()) {
runnerPermit.release();
if (!queue.isEmpty() && runnerPermit.tryAcquire()) {
executor.submit(this);
} else if (isTerminated()) {
termination.countDown();
}
} else {
executor.submit(this);
}
}
}
});
代码示例来源:origin: wildfly/wildfly
public void setMaxThreads(final int maxThreads) {
Assert.checkMinimumParameter("maxThreads", 0, maxThreads);
synchronized (lock) {
final int old = this.maxThreads;
final int diff = old - maxThreads;
if (diff < 0) {
limitSemaphore.release(-diff);
} else if (diff > 0) {
if (! limitSemaphore.tryAcquire(diff)) {
throw Messages.msg.cannotReduceMaxBelowCurrent();
}
}
this.maxThreads = maxThreads;
}
}
代码示例来源:origin: apache/usergrid
private void maybeFlush() {
final int count = cachedOperations.incrementAndGet();
//no op
if ( count < flushCount ) {
return;
}
//another thread is writing, no op, just return
if ( !writeSemaphore.tryAcquire() ) {
return;
}
final long failed = entitiesFailed.get();
final long written = entitiesWritten.get();
final String message;
if ( failed > 0 ) {
message = "Failed to import " + failed
+ " entities. Successfully imported " + written + " entities";
}
else {
message = "Successfully imported " + written + " entities";
}
updateFileImport( FileImport.State.STARTED, message );
cachedOperations.addAndGet( flushCount * -1 );
writeSemaphore.release();
}
代码示例来源: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: apache/flink
@Override
public void processWatermark(Watermark mark) throws Exception {
if (!semaphore.tryAcquire()) {
Assert.fail("Concurrent invocation of operator functions.");
}
semaphore.release();
}
}
内容来源于网络,如有侵权,请联系作者删除!