本文整理匯總了Java中java.util.concurrent.Exchanger.exchange方法的典型用法代碼示例。如果您正苦於以下問題:Java Exchanger.exchange方法的具體用法?Java Exchanger.exchange怎麽用?Java Exchanger.exchange使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.Exchanger
的用法示例。
在下文中一共展示了Exchanger.exchange方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testRateLimit
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
public void testRateLimit() throws Exception {
final TestProducer p = new TestProducer();
MockStages.setSourceCapture(p);
final ProductionPipeline pipeline = createProductionPipeline(DeliveryGuarantee.AT_MOST_ONCE, true, 10L, PipelineType.DEFAULT);
pipeline.registerStatusListener(new MyStateListener());
final Exchanger<Double> rate = new Exchanger<>();
new Thread() {
@Override
public void run() {
try {
long start = System.nanoTime();
pipeline.run();
rate.exchange(p.count.doubleValue() * 1000 * 1000 * 1000 / (System.nanoTime() - start));
} catch (Exception ex) {
}
}
}.start();
Thread.sleep(10000);
pipeline.stop();
Double rateAchieved = rate.exchange(0.0);
// To account for the slight loss of precision, we compare the "long-ified" versions.
Assert.assertTrue(rateAchieved.longValue() <= 10);
}
示例2: testNotCloseZkWhenPending
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
public void testNotCloseZkWhenPending() throws Exception {
ZooKeeper mockedZK = mock(ZooKeeper.class);
Exchanger<AsyncCallback.DataCallback> exchanger = new Exchanger<>();
doAnswer(i -> {
exchanger.exchange(i.getArgument(2));
return null;
}).when(mockedZK).getData(anyString(), anyBoolean(),
any(AsyncCallback.DataCallback.class), any());
doAnswer(i -> null).when(mockedZK).close();
when(mockedZK.getState()).thenReturn(ZooKeeper.States.CONNECTED);
RO_ZK.zookeeper = mockedZK;
CompletableFuture<byte[]> future = RO_ZK.get(PATH);
AsyncCallback.DataCallback callback = exchanger.exchange(null);
// 2 * keep alive time to ensure that we will not close the zk when there are pending requests
Thread.sleep(6000);
assertNotNull(RO_ZK.zookeeper);
verify(mockedZK, never()).close();
callback.processResult(Code.OK.intValue(), PATH, null, DATA, null);
assertArrayEquals(DATA, future.get());
// now we will close the idle connection.
waitForIdleConnectionClosed();
verify(mockedZK, times(1)).close();
}
示例3: doSendMessage
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Override
protected void doSendMessage(Message message) throws IOException {
// the http stack is intended to send back only coap responses
// check if the message is a response
if (message instanceof Response) {
// retrieve the request linked to the response
Response response = (Response) message;
Request request = response.getRequest();
LOG.info("Handling response for request: " + request);
// fill the exchanger with the incoming response
Exchanger<Response> exchanger = exchangeMap.get(request);
try {
exchanger.exchange(response);
} catch (InterruptedException e) {
LOG.warning("Exchange interrupted: " + e.getMessage());
// remove the entry from the map
exchangeMap.remove(request);
return;
}
LOG.info("Exchanged correctly");
}
}
示例4: paneFor
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
private JEditorPane paneFor(FileObject src, String fileName, String code) throws Exception, DataObjectNotFoundException, IOException {
FileObject fromFO = FileUtil.createData(src, fileName);
TestUtilities.copyStringToFile(fromFO, code);
DataObject od = DataObject.find(fromFO);
final EditorCookie.Observable ec = od.getCookie(EditorCookie.Observable.class);
final Exchanger<JEditorPane> exch = new Exchanger<>();
class L implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
if (!EditorCookie.Observable.PROP_OPENED_PANES.equals(evt.getPropertyName())) {
return;
}
// we are in AWT
JEditorPane[] panes = ec.getOpenedPanes();
if (panes == null) {
return;
}
exch.exchange(panes[0]);
} catch (InterruptedException ex) {
}
}
}
L listener = new L();
ec.addPropertyChangeListener(listener);
JEditorPane pane = null;
try {
ec.open();
ec.openDocument().putProperty(Language.class, JavaTokenId.language());
pane = exch.exchange(null, 5, TimeUnit.SECONDS);
} finally {
ec.removePropertyChangeListener(listener);
}
assertNotNull("Editor pane not opened", pane);
return pane;
}
示例5: putAsyncEvent
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
private void putAsyncEvent(MetricsUpdateEvent event) {
try {
Exchanger<MetricsUpdateEvent> async = asyncEventRef.getAndSet(null);
if (async != null) {
async.exchange(event);
}
} catch (InterruptedException e) {
// No-op.
}
}
示例6: waitForOtherThreadAndPassObject
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
protected static Object waitForOtherThreadAndPassObject(final Exchanger exchanger, Object object)
{
Object result = null;
try
{
result = exchanger.exchange(object);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return result;
}
示例7: waitForOtherThreadAndPassObject
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
protected Object waitForOtherThreadAndPassObject(final Exchanger exchanger, Object object)
{
Object result = null;
try
{
getLogger().debug("waiting..");
result = exchanger.exchange(object);
getLogger().debug("done waiting");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return result;
}
示例8: exchange
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
private static <T> T exchange(Exchanger<T> exchanger, T value) {
try {
return exchanger.exchange(value);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
示例9: testHandleAsync
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
public void testHandleAsync() throws Exception {
ByteBuf buf = Unpooled.buffer();
buf.writeByte(1);
NettyMessage msg = new NettyMessage(buf, new Codec<Object>() {
@Override
public boolean isStateful() {
return false;
}
@Override
public Class<Object> baseType() {
return Object.class;
}
@Override
public Object decode(DataReader in) throws IOException {
return in.readByte();
}
@Override
public void encode(Object obj, DataWriter out) throws IOException {
throw new AssertionError("Should not be called.");
}
});
Object val;
ExecutorService thread = Executors.newSingleThreadExecutor();
try {
Exchanger<Object> ref = new Exchanger<>();
msg.handleAsync(thread,
m -> {
try {
ref.exchange(m);
} catch (InterruptedException e) {
// No-op.
}
},
err -> {
// No-op.
}
);
val = ref.exchange(null);
} finally {
thread.shutdownNow();
thread.awaitTermination(3, TimeUnit.SECONDS);
}
assertEquals((byte)1, val);
assertEquals(1, buf.refCnt());
}
示例10: testHandleAsyncError
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
public void testHandleAsyncError() throws Exception {
ByteBuf buf = Unpooled.buffer();
buf.writeByte(1);
NettyMessage msg = new NettyMessage(buf, new Codec<Object>() {
@Override
public boolean isStateful() {
return false;
}
@Override
public Class<Object> baseType() {
return Object.class;
}
@Override
public Object decode(DataReader in) throws IOException {
throw TEST_ERROR;
}
@Override
public void encode(Object obj, DataWriter out) throws IOException {
throw new AssertionError("Should not be called.");
}
});
Throwable expected;
ExecutorService thread = Executors.newSingleThreadExecutor();
try {
Exchanger<Throwable> ref = new Exchanger<>();
msg.handleAsync(thread,
m -> {
// No-op.
},
err -> {
try {
ref.exchange(err);
} catch (InterruptedException e) {
// No-op.
}
}
);
expected = ref.exchange(null);
} finally {
thread.shutdownNow();
thread.awaitTermination(3, TimeUnit.SECONDS);
}
assertTrue(expected.toString(), expected instanceof CodecException);
assertSame(TEST_ERROR, expected.getCause());
assertEquals(1, buf.refCnt());
}
示例11: callCountedMethodOnce
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
@InSequence(3)
public void callCountedMethodOnce() throws InterruptedException, TimeoutException {
assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
Counter counter = registry.getCounters().get(COUNTER_NAME);
// Call the counted method, block and assert it's been counted
final Exchanger<Long> exchanger = new Exchanger<>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
exchanger.exchange(bean.monotonicCountedMethod(new Callable<Long>() {
@Override
public Long call() throws Exception {
exchanger.exchange(0L);
return exchanger.exchange(0L);
}
}));
}
catch (InterruptedException cause) {
throw new RuntimeException(cause);
}
}
});
final AtomicInteger uncaught = new AtomicInteger();
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
uncaught.incrementAndGet();
}
});
thread.start();
// Wait until the method is executing and make sure that the counter has been incremented
exchanger.exchange(0L, 5L, TimeUnit.SECONDS);
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.incrementAndGet())));
// Exchange the result and unblock the method execution
Long random = 1 + Math.round(Math.random() * (Long.MAX_VALUE - 1));
exchanger.exchange(random, 5L, TimeUnit.SECONDS);
// Wait until the method has returned
assertThat("Counted method return value is incorrect", exchanger.exchange(0L), is(equalTo(random)));
// Then make sure that the counter has not been decremented
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
// Finally make sure calling thread is returns correctly
thread.join();
assertThat("Exception thrown in method call thread", uncaught.get(), is(equalTo(0)));
}
示例12: callCountedMethodOnce
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
@InSequence(3)
public void callCountedMethodOnce() throws InterruptedException, TimeoutException {
assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
Counter counter = registry.getCounters().get(COUNTER_NAME);
// Call the counted method, block and assert it's been counted
final Exchanger<Long> exchanger = new Exchanger<>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
exchanger.exchange(bean.countedMethod(new Callable<Long>() {
@Override
public Long call() throws Exception {
exchanger.exchange(0L);
return exchanger.exchange(0L);
}
}));
}
catch (InterruptedException cause) {
throw new RuntimeException(cause);
}
}
});
final AtomicInteger uncaught = new AtomicInteger();
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
uncaught.incrementAndGet();
}
});
thread.start();
// Wait until the method is executing and make sure that the counter has been incremented
exchanger.exchange(0L, 5L, TimeUnit.SECONDS);
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.incrementAndGet())));
// Exchange the result and unblock the method execution
Long random = 1 + Math.round(Math.random() * (Long.MAX_VALUE - 1));
exchanger.exchange(random, 5L, TimeUnit.SECONDS);
// Wait until the method has returned
assertThat("Counted method return value is incorrect", exchanger.exchange(0L), is(equalTo(random)));
// Then make sure that the counter has been decremented
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.decrementAndGet())));
// Finally make sure calling thread is returns correctly
thread.join();
assertThat("Exception thrown in method call thread", uncaught.get(), is(equalTo(0)));
}
示例13: multipleTopLevelRulesDontBlockEachOther
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
public void multipleTopLevelRulesDontBlockEachOther() throws Exception {
Exchanger<Boolean> exchanger = new Exchanger<>();
Step exchangerStep =
new AbstractExecutionStep("interleaved_step") {
@Override
public StepExecutionResult execute(ExecutionContext context)
throws IOException, InterruptedException {
try {
// Forces both rules to wait for the other at this point.
exchanger.exchange(true, 6, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
return StepExecutionResults.SUCCESS;
}
};
BuildRule interleavedRuleOne =
createRule(
filesystem,
resolver,
/* deps */ ImmutableSortedSet.of(),
/* buildSteps */ ImmutableList.of(exchangerStep),
/* postBuildSteps */ ImmutableList.of(),
/* pathToOutputFile */ null,
ImmutableList.of(InternalFlavor.of("interleaved-1")));
resolver.addToIndex(interleavedRuleOne);
BuildRule interleavedRuleTwo =
createRule(
filesystem,
resolver,
/* deps */ ImmutableSortedSet.of(),
/* buildSteps */ ImmutableList.of(exchangerStep),
/* postBuildSteps */ ImmutableList.of(),
/* pathToOutputFile */ null,
ImmutableList.of(InternalFlavor.of("interleaved-2")));
resolver.addToIndex(interleavedRuleTwo);
// The engine needs a couple of threads to ensure that it can schedule multiple steps at the
// same time.
ListeningExecutorService executorService =
listeningDecorator(Executors.newFixedThreadPool(4));
try (CachingBuildEngine cachingBuildEngine =
cachingBuildEngineFactory().setExecutorService(executorService).build()) {
BuildEngineResult engineResultOne =
cachingBuildEngine.build(
buildContext, TestExecutionContext.newInstance(), interleavedRuleOne);
BuildEngineResult engineResultTwo =
cachingBuildEngine.build(
buildContext, TestExecutionContext.newInstance(), interleavedRuleTwo);
assertThat(engineResultOne.getResult().get().getStatus(), equalTo(BuildRuleStatus.SUCCESS));
assertThat(engineResultTwo.getResult().get().getStatus(), equalTo(BuildRuleStatus.SUCCESS));
}
executorService.shutdown();
}
示例14: callCountedMethodOnce
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
@InSequence(3)
public void callCountedMethodOnce() throws InterruptedException, TimeoutException {
assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
Counter counter = registry.getCounters().get(COUNTER_NAME);
// Call the counted method, block and assert it's been counted
final Exchanger<Long> exchanger = new Exchanger<>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
exchanger.exchange(bean.monotonicCountedMethod(new Callable<Long>() {
@Override
public Long call() throws Exception {
exchanger.exchange(0L);
return exchanger.exchange(0L);
}
}));
} catch (InterruptedException cause) {
throw new RuntimeException(cause);
}
}
});
final AtomicInteger uncaught = new AtomicInteger();
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
uncaught.incrementAndGet();
}
});
thread.start();
// Wait until the method is executing and make sure that the counter has been incremented
exchanger.exchange(0L, 5L, TimeUnit.SECONDS);
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.incrementAndGet())));
// Exchange the result and unblock the method execution
Long random = 1 + Math.round(Math.random() * (Long.MAX_VALUE - 1));
exchanger.exchange(random, 5L, TimeUnit.SECONDS);
// Wait until the method has returned
assertThat("Counted method return value is incorrect", exchanger.exchange(0L), is(equalTo(random)));
// Then make sure that the counter has not been decremented
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
// Finally make sure calling thread is returns correctly
thread.join();
assertThat("Exception thrown in method call thread", uncaught.get(), is(equalTo(0)));
}
示例15: callCountedMethodOnce
import java.util.concurrent.Exchanger; //導入方法依賴的package包/類
@Test
@InSequence(3)
public void callCountedMethodOnce() throws InterruptedException, TimeoutException {
assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
Counter counter = registry.getCounters().get(COUNTER_NAME);
// Call the counted method, block and assert it's been counted
final Exchanger<Long> exchanger = new Exchanger<>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
exchanger.exchange(bean.countedMethod(new Callable<Long>() {
@Override
public Long call() throws Exception {
exchanger.exchange(0L);
return exchanger.exchange(0L);
}
}));
} catch (InterruptedException cause) {
throw new RuntimeException(cause);
}
}
});
final AtomicInteger uncaught = new AtomicInteger();
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
uncaught.incrementAndGet();
}
});
thread.start();
// Wait until the method is executing and make sure that the counter has been incremented
exchanger.exchange(0L, 5L, TimeUnit.SECONDS);
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.incrementAndGet())));
// Exchange the result and unblock the method execution
Long random = 1 + Math.round(Math.random() * (Long.MAX_VALUE - 1));
exchanger.exchange(random, 5L, TimeUnit.SECONDS);
// Wait until the method has returned
assertThat("Counted method return value is incorrect", exchanger.exchange(0L), is(equalTo(random)));
// Then make sure that the counter has been decremented
assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.decrementAndGet())));
// Finally make sure calling thread is returns correctly
thread.join();
assertThat("Exception thrown in method call thread", uncaught.get(), is(equalTo(0)));
}