本文整理汇总了Java中java.util.concurrent.Semaphore.tryAcquire方法的典型用法代码示例。如果您正苦于以下问题:Java Semaphore.tryAcquire方法的具体用法?Java Semaphore.tryAcquire怎么用?Java Semaphore.tryAcquire使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.Semaphore
的用法示例。
在下文中一共展示了Semaphore.tryAcquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getSnap
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public static DataSnapshot getSnap(Query ref) throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
// Hack to get around final reference issue
final List<DataSnapshot> snapshotList = new ArrayList<>(1);
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
snapshotList.add(snapshot);
semaphore.release(1);
}
@Override
public void onCancelled(DatabaseError error) {
semaphore.release(1);
}
});
semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
return snapshotList.get(0);
}
示例2: waitForProcessedStoring
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Override
public void waitForProcessedStoring(VCSFileProxy file, String caller) {
Semaphore s;
synchronized(proccessedFiles) {
s = proccessedFiles.get(file);
}
if(s != null) {
long l = System.currentTimeMillis();
try {
long t9Timeout = getT9LockReleaseTimeOut();
long timeout = t9Timeout >= 0 ? t9Timeout : LOCK_TIMEOUT;
boolean aquired = s.tryAcquire(timeout, TimeUnit.SECONDS);
if(aquired) {
s.release();
} else {
LOG.log(Level.WARNING, "{0} Releasing lock on file: {1}", new Object[] {caller, FileUtils.getPath(file)}); // NOI18N
synchronized(proccessedFiles) {
proccessedFiles.remove(file);
}
}
} catch (InterruptedException ex) {
// nothing
}
LOG.log(Level.FINER, "{0} for file {1} was blocked {2} millis.", new Object[] {caller, FileUtils.getPath(file), System.currentTimeMillis() - l}); // NOI18N
}
}
示例3: waitForResponse
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private ActionResponseData waitForResponse(ActionRequestData requestData, long timeout) {
Semaphore semaphore = new Semaphore(0);
AtomicReference<ActionResponseData> response = new AtomicReference<>();
actionHandler.addActionRequest(requestData, actionResponseData -> {
response.compareAndSet(null, actionResponseData);
semaphore.release();
});
try {
if(semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
return response.get();
} else {
LOGGER.warn("Action response timed out");
}
} catch (InterruptedException e) {
LOGGER.warn("Action response interrupted", e);
}
return null;
}
示例4: enterIOCriticalSection
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public void enterIOCriticalSection(String key) throws IOException {
// http://dmy999.com/article/34/correct-use-of-concurrenthashmap
Semaphore creationSemaphore = map.get(key);
if(creationSemaphore == null) {
Semaphore newCreationSemaphore = new Semaphore(1, true);
creationSemaphore = map.putIfAbsent(key, newCreationSemaphore);
if(creationSemaphore == null) {
creationSemaphore = newCreationSemaphore;
if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("new Semaphore added for key " + key);
}
}
}
try {
boolean retval = creationSemaphore.tryAcquire(10, TimeUnit.SECONDS);
if (!retval) {
throw new IOException("Could not acquire IO Semaphore'" + key
+ "' after 10 seconds -- giving up ");
}
} catch (InterruptedException e) {
throw new IOException("exception in acquiring sem");
}
}
示例5: doTestUnloadableInStaticFieldIfClosed
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private WeakReference<ClassLoader> doTestUnloadableInStaticFieldIfClosed() throws Exception {
final URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
final URL[] urls = myLoader.getURLs();
URLClassLoader sepLoader = new URLClassLoader(urls, myLoader.getParent());
Class<?> frqC = FinalizableReferenceQueue.class;
Class<?> sepFrqC = sepLoader.loadClass(frqC.getName());
assertNotSame(frqC, sepFrqC);
Class<?> sepFrqSystemLoaderC =
sepLoader.loadClass(FinalizableReferenceQueue.SystemLoader.class.getName());
Field disabled = sepFrqSystemLoaderC.getDeclaredField("disabled");
disabled.setAccessible(true);
disabled.set(null, true);
Class<?> frqUserC = FrqUser.class;
Class<?> sepFrqUserC = sepLoader.loadClass(frqUserC.getName());
assertNotSame(frqUserC, sepFrqUserC);
assertSame(sepLoader, sepFrqUserC.getClassLoader());
Callable<?> sepFrqUser = (Callable<?>) sepFrqUserC.newInstance();
WeakReference<?> finalizableWeakReference = (WeakReference<?>) sepFrqUser.call();
GcFinalization.awaitClear(finalizableWeakReference);
Field sepFrqUserFinalizedF = sepFrqUserC.getField("finalized");
Semaphore finalizeCount = (Semaphore) sepFrqUserFinalizedF.get(null);
boolean finalized = finalizeCount.tryAcquire(5, TimeUnit.SECONDS);
assertTrue(finalized);
Field sepFrqUserFrqF = sepFrqUserC.getField("frq");
Closeable frq = (Closeable) sepFrqUserFrqF.get(null);
frq.close();
return new WeakReference<ClassLoader>(sepLoader);
}
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:37,代码来源:FinalizableReferenceQueueClassLoaderUnloadingTest.java
示例6: checkTreeCache
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private static void checkTreeCache(CuratorFramework curatorFramework, String path) throws Exception {
final Semaphore semaphore = new Semaphore(0);
TreeCache treeCache = TreeCache.newBuilder(curatorFramework, path)
.setCacheData(true)
.setMaxDepth(3)
.build();
if (treeCache == null) {
LOGGER.error("treeCache is null");
}
treeCache.getListenable().addListener((client, event) -> {
if (event.getType().equals(TreeCacheEvent.Type.INITIALIZED)) {
semaphore.release();
}
});
treeCache.start();
semaphore.tryAcquire(2, TimeUnit.SECONDS);
Map<String, ChildData> map = treeCache.getCurrentChildren("/propertyService");
if (map == null) {
LOGGER.error("map is null");
}
map.entrySet().forEach(entry -> {
LOGGER.info("{} - {}", entry.getKey(), Bytes.toString(entry.getValue().getData()));
});
}
示例7: retrievePayment
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@RequestMapping(path = "/api/payment/v5", method = PUT)
public String retrievePayment(String retrievePaymentPayload, HttpServletResponse response) throws Exception {
String traceId = UUID.randomUUID().toString();
String customerId = "0815"; // get somehow from retrievePaymentPayload
long amount = 15; // get somehow from retrievePaymentPayload
Semaphore newSemaphore = NotifySemaphorAdapter.newSemaphore(traceId);
ProcessInstance pi = retrievePayment(traceId, customerId, amount);
boolean finished = newSemaphore.tryAcquire(500, TimeUnit.MILLISECONDS);
NotifySemaphorAdapter.removeSemaphore(traceId);
if (finished) {
HistoricVariableInstance historicVariableInstance = camunda.getHistoryService().createHistoricVariableInstanceQuery()
.processInstanceId(pi.getId()) //
.variableName("paymentTransactionId") //
.singleResult();
if (historicVariableInstance!=null) {
String paymentTransactionId = (String)historicVariableInstance.getValue();
return "{\"status\":\"completed\", \"traceId\": \"" + traceId + "\", \"paymentTransactionId\": \""+paymentTransactionId+"\"}";
} else {
return "{\"status\":\"completed\", \"traceId\": \"" + traceId + "\", \"payedByCredit\": \"true\"}";
}
} else {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
return "{\"status\":\"pending\", \"traceId\": \"" + traceId + "\"}";
}
}
示例8: testExecuteWritesStdoutToTheStdoutListener
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testExecuteWritesStdoutToTheStdoutListener() throws Throwable {
final JobExecutor jobExecutor = getInstance();
final String msgSuppliedToEcho = generateRandomString();
final PersistedJob req =
standardRequestWithCommand("echo", msgSuppliedToEcho);
final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
final Subject<byte[]> stdoutSubject = PublishSubject.create();
stdoutSubject.subscribe(bytes ->
bytesEchoedToStdout.getAndUpdate(existingBytes ->
Bytes.concat(existingBytes, bytes)));
final Semaphore s = new Semaphore(1);
s.acquire();
stdoutSubject.doOnComplete(s::release).subscribe();
final JobEventListeners listeners =
createStdoutListener(stdoutSubject);
jobExecutor.execute(req, listeners);
s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);
final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();
assertThat(stringFromStdout).isEqualTo(msgSuppliedToEcho);
}
示例9: testExecuteWritesStderrToTheStderrListener
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testExecuteWritesStderrToTheStderrListener() throws Throwable {
final JobExecutor jobExecutor = getInstance();
final String msgSuppliedToEcho = generateRandomString();
final String bashArg = "echo " + msgSuppliedToEcho + " 1>&2"; // TODO: Naughty.
final PersistedJob req =
standardRequestWithCommand("bash", "-c", bashArg);
final AtomicReference<byte[]> bytesEchoedToStderr = new AtomicReference<>(new byte[]{});
final Subject<byte[]> stderrSubject = PublishSubject.create();
stderrSubject.subscribe(bytes ->
bytesEchoedToStderr.getAndUpdate(existingBytes ->
Bytes.concat(existingBytes, bytes)));
final Semaphore s = new Semaphore(1);
s.acquire();
stderrSubject.doOnComplete(s::release).subscribe();
final JobEventListeners listeners =
createStderrListener(stderrSubject);
jobExecutor.execute(req, listeners);
s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);
final String stringFromStderr = new String(bytesEchoedToStderr.get()).trim();
assertThat(stringFromStderr).isEqualTo(msgSuppliedToEcho);
}
示例10: main
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
for (Semaphore sem : new Semaphore[]{ new Semaphore(0),
new Semaphore(0, false),
new Semaphore(0, true)})
for (int delay : new int[] {0, 1})
for (int i = 0; i < 3; i++)
if (sem.tryAcquire(delay, TimeUnit.MILLISECONDS))
throw new Error("Acquired Semaphore with no permits!");
System.out.println("Done!");
}
示例11: handleWaitingForLog
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private void handleWaitingForLog(String containerId, Semaphore ready) throws DockerException, InterruptedException {
final LogStream logStream = dockerClient.logs(containerId,
DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr(), DockerClient.LogsParam.follow());
LOGGER.debug("Waiting for log snippet '{}'", waitForLog);
new Thread(() -> {
try {
while (logStream.hasNext()) {
final LogMessage msg = logStream.next();
final String logStr = StandardCharsets.UTF_8.decode(msg.content()).toString();
LOGGER.debug("CONTAINER: {}", logStr);
if (logStr.contains(waitForLog)) {
ready.release();
return;
}
}
} finally {
logStream.close();
}
}).start();
if (!ready.tryAcquire(waitForLogTimeout, TimeUnit.MILLISECONDS)) {
Assert.fail(String.format(
"Did not observe desired Docker container log snippet within %d ms",
waitForLogTimeout));
}
}
示例12: testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout() throws InterruptedException {
final Subject<byte[]> stdoutSubject = ReplaySubject.create();
final byte[] expectedStdoutBytes = generateRandomBytes();
stdoutSubject.onNext(expectedStdoutBytes);
final JobExecutor jobExecutor = MockJobExecutor.thatUses(stdoutSubject, Observable.never());
final JobManager jobManager = createManagerWith(jobExecutor);
final Semaphore s = new Semaphore(1);
s.acquire();
final JobEventListeners listeners = JobEventListeners.createStdoutListener(new Observer<byte[]>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {}
@Override
public void onNext(@NonNull byte[] bytes) {
assertThat(bytes).isEqualTo(expectedStdoutBytes);
s.release();
}
@Override
public void onError(@NonNull Throwable throwable) {
fail("Error from observable");
s.release();
}
@Override
public void onComplete() {}
});
jobManager.submit(STANDARD_VALID_REQUEST, listeners);
if (!s.tryAcquire(1, SECONDS)) {
fail("Timed out before any bytes received");
}
}
示例13: waitFor
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public static void waitFor(Semaphore semaphore, int count, long timeout, TimeUnit unit)
throws InterruptedException {
boolean success = semaphore.tryAcquire(count, timeout, unit);
assertTrue("Operation timed out", success);
}
示例14: testSerializeDoesntLockDataNodeWhileWriting
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
DataTree tree = new DataTree();
tree.createNode("/marker", new byte[] {42}, null, -1, 1, 1, 1);
final DataNode markerNode = tree.getNode("/marker");
final AtomicBoolean ranTestCase = new AtomicBoolean();
DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
BinaryOutputArchive oa = new BinaryOutputArchive(out) {
@Override
public void writeRecord(Record r, String tag) throws IOException {
// Need check if the record is a DataNode instance because of changes in ZOOKEEPER-2014
// which adds default ACL to config node.
if (r instanceof DataNode) {
DataNode node = (DataNode) r;
if (node.data.length == 1 && node.data[0] == 42) {
final Semaphore semaphore = new Semaphore(0);
new Thread(new Runnable() {
@Override
public void run() {
synchronized (markerNode) {
//When we lock markerNode, allow writeRecord to continue
semaphore.release();
}
}
}).start();
try {
boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
//This is the real assertion - could another thread lock
//the DataNode we're currently writing
Assert.assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
ranTestCase.set(true);
}
}
super.writeRecord(r, tag);
}
};
tree.serialize(oa, "test");
//Let's make sure that we hit the code that ran the real assertion above
Assert.assertTrue("Didn't find the expected node", ranTestCase.get());
}
示例15: testExecuteStatements
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/** Test testExecuteStatements passes if no exceptions occur. */
public void testExecuteStatements() throws Exception {
SQLHistoryManager testableManager = new SQLHistoryManager() {
@Override
protected FileObject getConfigRoot() {
try {
return FileUtil.toFileObject(getWorkDir());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Override
protected String getRelativeHistoryPath() {
return "";
}
};
// History does not yet exists as file
assertNull(testableManager.getHistoryRoot(false));
testableManager.getSQLHistory().add(new SQLHistoryEntry("jdbc:// mysql", "select * from TRAVEL.PERSON", Calendar.getInstance().getTime()));
// History does not yet exists as file
testableManager.save();
assertNull(testableManager.getHistoryRoot(false));
testableManager.getSQLHistory().add(new SQLHistoryEntry("jdbc:// oracle", "select * from PERSON", Calendar.getInstance().getTime()));
final Semaphore s = new Semaphore(0);
PropertyChangeListener releasingListener =
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (SQLHistoryManager.PROP_SAVED.equals(
evt.getPropertyName())) {
s.release(); //release semaphore when data are saved
}
}
};
testableManager.addPropertyChangeListener(releasingListener);
testableManager.save();
// History does not yet exists as file
assertNull(testableManager.getHistoryRoot(false));
// Enforce writing of history
s.tryAcquire(6, TimeUnit.SECONDS);
testableManager.removePropertyChangeListener(releasingListener);
// History file need to exist now!
assertNotNull(testableManager.getHistoryRoot(false));
assertTrue(testableManager.getHistoryRoot(false).isData());
}