本文整理汇总了Java中java.util.concurrent.Semaphore.release方法的典型用法代码示例。如果您正苦于以下问题:Java Semaphore.release方法的具体用法?Java Semaphore.release怎么用?Java Semaphore.release使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.Semaphore
的用法示例。
在下文中一共展示了Semaphore.release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: saveChallenge
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
boolean saveChallenge(long tag, long challenge) {
Semaphore s = challengeMutex.get(tag);
if (s != null) {
synchronized (Messenger.this) {
challengeMap.put(tag, challenge);
challengeMutex.remove(tag);
}
s.release();
} else {
LOG.error("No challenge mutex object");
}
return true;
}
示例2: testWaitForItself
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public void testWaitForItself() {
final Semaphore s = new Semaphore(0);
class R implements Runnable {
int cnt;
volatile Task waitFor;
@Override
public void run() {
cnt++;
try {
s.acquire(); // Ensure waitFor != null.
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
waitFor.waitFinished();
}
}
R r = new R();
r.waitFor = new AWTTask(r, null);
s.release();
r.waitFor.waitFinished();
assertEquals("Executed once", 1, r.cnt);
}
示例3: 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
}
}
示例4: testCacheInvalidation
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testCacheInvalidation()
throws InterruptedException, TestFailure, TimeoutException {
List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
DatabaseReference reader = refs.get(0);
DatabaseReference writer = refs.get(1);
final AtomicBoolean startChecking = new AtomicBoolean(false);
final Semaphore ready = new Semaphore(0);
final ReadFuture future = new ReadFuture(reader.limitToLast(2),
new ReadFuture.CompletionCondition() {
@Override
public boolean isComplete(List<EventRecord> events) {
DataSnapshot snap = events.get(events.size() - 1).getSnapshot();
Object result = snap.getValue();
if (startChecking.compareAndSet(false, true) && result == null) {
ready.release(1);
return false;
}
// We already initialized the location, and now the remove has
// happened
// so that
// we have no more data
return startChecking.get() && result == null;
}
});
TestHelpers.waitFor(ready);
for (int i = 0; i < 4; ++i) {
writer.child("k" + i).setValueAsync(i);
}
writer.removeValueAsync();
future.timedGet();
}
示例5: testUpdateFiresCorrectEventWhenAllChildrenAreDeleted
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testUpdateFiresCorrectEventWhenAllChildrenAreDeleted()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
DatabaseReference writer = refs.get(0);
DatabaseReference reader = refs.get(1);
final ReadFuture writerFuture = ReadFuture.untilCountAfterNull(writer, 2);
new WriteFuture(writer, MapBuilder.of("a", 12)).timedGet();
final Semaphore semaphore = new Semaphore(0);
final ReadFuture readerFuture = new ReadFuture(reader, new ReadFuture.CompletionCondition() {
@Override
public boolean isComplete(List<EventRecord> events) {
if (events.size() == 1) {
semaphore.release();
}
return events.size() == 2;
}
});
TestHelpers.waitFor(semaphore);
writer.updateChildrenAsync(MapBuilder.of("a", null));
DataSnapshot snap = writerFuture.timedGet().get(1).getSnapshot();
assertNull(snap.getValue());
snap = readerFuture.timedGet().get(1).getSnapshot();
assertNull(snap.getValue());
}
示例6: testUpdateFiresCorrectEventOnChangedChildren
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testUpdateFiresCorrectEventOnChangedChildren()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
DatabaseReference writer = refs.get(0);
DatabaseReference reader = refs.get(1);
final ReadFuture writerFuture = ReadFuture.untilCountAfterNull(writer, 2);
new WriteFuture(writer, MapBuilder.of("a", 12)).timedGet();
final Semaphore semaphore = new Semaphore(0);
final ReadFuture readerFuture = new ReadFuture(reader, new ReadFuture.CompletionCondition() {
@Override
public boolean isComplete(List<EventRecord> events) {
if (events.size() == 1) {
semaphore.release();
}
return events.size() == 2;
}
});
TestHelpers.waitFor(semaphore);
writer.updateChildrenAsync(MapBuilder.of("a", 11));
DataSnapshot snap = writerFuture.timedGet().get(1).getSnapshot();
Map<String, Object> expected = MapBuilder.of("a", 11L);
TestHelpers.assertDeepEquals(expected, snap.getValue());
snap = readerFuture.timedGet().get(1).getSnapshot();
TestHelpers.assertDeepEquals(expected, snap.getValue());
}
示例7: testExceptionHandling
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testExceptionHandling() throws InterruptedException {
MockRunLoop runLoop = new MockRunLoop();
final Semaphore semaphore = new Semaphore(0);
UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
semaphore.release();
}
};
runLoop.setExceptionHandler(exceptionHandler);
assertSame(exceptionHandler, runLoop.getExceptionHandler());
try {
assertEquals(0, runLoop.getThreadPool().getCorePoolSize());
runLoop.scheduleNow(new Runnable() {
@Override
public void run() {
throw new RuntimeException("test error");
}
});
assertEquals(1, runLoop.getThreadPool().getCorePoolSize());
semaphore.acquire();
synchronized (runLoop.errors) {
if (runLoop.errors.isEmpty()) {
runLoop.errors.wait(TestUtils.TEST_TIMEOUT_MILLIS);
}
}
assertEquals(1, runLoop.errors.size());
} finally {
runLoop.getExecutorService().shutdownNow();
}
}
示例8: testReleaseIAE
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public void testReleaseIAE(boolean fair) {
Semaphore s = new Semaphore(10, fair);
try {
s.release(-1);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
示例9: testDrainPermits
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public void testDrainPermits(boolean fair) {
Semaphore s = new Semaphore(0, fair);
assertEquals(0, s.availablePermits());
assertEquals(0, s.drainPermits());
s.release(10);
assertEquals(10, s.availablePermits());
assertEquals(10, s.drainPermits());
assertEquals(0, s.availablePermits());
assertEquals(0, s.drainPermits());
}
示例10: invoke
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* Processes a method invocation on a proxy instance and returns
* the result. This method will be invoked on an invocation handler
* when a method is invoked on a proxy instance that it is
* associated with.
*
* @param proxy the proxy instance that the method was invoked on
* @param method the {@code Method} instance corresponding to
* the interface method invoked on the proxy instance. The declaring
* class of the {@code Method} object will be the interface that
* the method was declared in, which may be a superinterface of the
* proxy interface that the proxy class inherits the method through.
* @param args an array of objects containing the values of the
* arguments passed in the method invocation on the proxy instance,
* or {@code null} if interface method takes no arguments.
* Arguments of primitive types are wrapped in instances of the
* appropriate primitive wrapper class, such as
* {@code java.lang.Integer} or {@code java.lang.Boolean}.
* @return the value to return from the method invocation on the
* proxy instance. If the declared return type of the interface
* method is a primitive type, then the value returned by
* this method must be an instance of the corresponding primitive
* wrapper class; otherwise, it must be a type assignable to the
* declared return type. If the value returned by this method is
* {@code null} and the interface method's return type is
* primitive, then a {@code NullPointerException} will be
* thrown by the method invocation on the proxy instance. If the
* value returned by this method is otherwise not compatible with
* the interface method's declared return type as described above,
* a {@code ClassCastException} will be thrown by the method
* invocation on the proxy instance.
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
RemoteAccessCommunicationRequest request = new RemoteAccessCommunicationRequest(method.getName(), clazz, uuid, args);
Semaphore semaphore = remoteAccessBlockRegistration.await(request);
sender.objectToServer(request);
semaphore.acquire();
RemoteAccessCommunicationResponse response = remoteAccessBlockRegistration.getResponse(uuid);
remoteAccessBlockRegistration.clearResult(uuid);
remoteAccessBlockRegistration.clearSemaphore(uuid);
semaphore.release();
if(response.getThrownThrowable() != null) {
testForThrow(clazz, response.getThrownThrowable());
}
return response.getResult();
}
示例11: testReleaseAcquireDifferentThreads
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public void testReleaseAcquireDifferentThreads(boolean fair,
final AcquireMethod acquirer) {
final Semaphore s = new Semaphore(0, fair);
final int rounds = 4;
long startTime = System.nanoTime();
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() throws InterruptedException {
for (int i = 0; i < rounds; i++) {
assertFalse(s.hasQueuedThreads());
if (i % 2 == 0)
acquirer.acquire(s);
else
acquirer.acquire(s, 3);
}}});
for (int i = 0; i < rounds; i++) {
while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
Thread.yield();
assertTrue(t.isAlive());
if (i % 2 == 0)
s.release();
else
s.release(3);
}
awaitTermination(t);
assertEquals(0, s.availablePermits());
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
示例12: fileCreateFromMove
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Override
public void fileCreateFromMove(VCSFileProxy from, VCSFileProxy to, long ts) {
Semaphore s = lock(from, "fileCreateFromMove"); // NOI18N
try {
if(lastModified(to) > 0) {
return;
}
fileCreateImpl(to, ts, FileUtils.getPath(from), FileUtils.getPath(to));
} catch (IOException ioe) {
LocalHistory.LOG.log(Level.WARNING, null, ioe);
} finally {
if(s != null) s.release();
}
fireChanged(to, ts);
}
示例13: setupWeakSubclass
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* Create a CleanableCase for a WeakReference.
* @param cleaner the cleaner to use
* @param obj an object or null to create a new Object
* @return a new CleanableCase preset with the object, cleanup, and semaphore
*/
static CleanableCase setupWeakSubclass(Cleaner cleaner, Object obj) {
if (obj == null) {
obj = new Object();
}
Semaphore s1 = new Semaphore(0);
Cleaner.Cleanable c1 = new WeakCleanable<Object>(obj, cleaner) {
protected void performCleanup() {
s1.release();
}
};
return new CleanableCase(new WeakReference<>(obj, null), c1, s1);
}
示例14: getStoreEntry
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Override
public StoreEntry getStoreEntry(VCSFileProxy file, long ts) {
Semaphore s = lock(file, "getStoreEntry"); // NOI18N
try {
return getStoreEntryIntern(file, ts);
} finally {
if(s != null) s.release();
}
}
示例15: testAddingListensForTheSamePathDoesNotCheckFail
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testAddingListensForTheSamePathDoesNotCheckFail() throws Throwable {
// This bug manifests itself if there's a hierarchy of query listener,
// default listener and
// one-time listener underneath. During one-time listener registration,
// sync-tree traversal
// stopped as soon as it found a complete server cache (this is the case
// for not indexed query
// view). The problem is that the same traversal was looking for a
// ancestor default view, and
// the early exit prevented from finding the default listener above the
// one-time listener. Event
// removal code path wasn't removing the listener because it stopped as
// soon as it found the
// default view. This left the zombie one-time listener and check failed
// on the second attempt
// to create a listener for the same path (asana#61028598952586).
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
final Semaphore semaphore = new Semaphore(0);
ValueEventListener dummyListen = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
semaphore.release();
}
@Override
public void onCancelled(DatabaseError error) {
}
};
ref.child("child").setValueAsync(TestHelpers.fromJsonString("{\"name\": \"John\"}"));
ref.orderByChild("name").equalTo("John").addValueEventListener(dummyListen);
ref.child("child").addValueEventListener(dummyListen);
TestHelpers.waitFor(semaphore, 2);
ref.child("child").child("favoriteToy").addListenerForSingleValueEvent(dummyListen);
TestHelpers.waitFor(semaphore, 1);
ref.child("child").child("favoriteToy").addListenerForSingleValueEvent(dummyListen);
TestHelpers.waitFor(semaphore, 1);
ref.removeEventListener(dummyListen);
ref.child("child").removeEventListener(dummyListen);
}