下面列出了java.util.concurrent.atomic.AtomicBoolean#getAndSet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Tests that the send operation is being retried.
*/
@Test
public void testRetriableSendOperationIfConnectionErrorOrServiceUnavailable() throws Exception {
final PingRestHandler pingRestHandler = new PingRestHandler(
FutureUtils.completedExceptionally(new RestHandlerException("test exception", HttpResponseStatus.SERVICE_UNAVAILABLE)),
CompletableFuture.completedFuture(EmptyResponseBody.getInstance()));
try (final TestRestServerEndpoint restServerEndpoint = createRestServerEndpoint(pingRestHandler)) {
RestClusterClient<?> restClusterClient = createRestClusterClient(restServerEndpoint.getServerAddress().getPort());
try {
final AtomicBoolean firstPollFailed = new AtomicBoolean();
failHttpRequest = (messageHeaders, messageParameters, requestBody) ->
messageHeaders instanceof PingRestHandlerHeaders && !firstPollFailed.getAndSet(true);
restClusterClient.sendRequest(PingRestHandlerHeaders.INSTANCE).get();
} finally {
restClusterClient.close();
}
}
}
private static void maybeRefreshJars(Collection<File> missingJars, AtomicBoolean pendingRefresh) {
// We probably need to refresh the virtual file system to find these files, but we can't refresh
// here because we're in a read action. We also can't use the async refreshIoFiles since it
// still tries to refresh the IO files synchronously. A global async refresh can't find new
// files in the ObjFS since we're not watching it.
// We need to do our own asynchronous refresh, and guard it with a flag to prevent the event
// queue from overflowing.
if (!missingJars.isEmpty() && !pendingRefresh.getAndSet(true)) {
ApplicationManager.getApplication()
.invokeLater(
() -> {
LocalFileSystem.getInstance().refreshIoFiles(missingJars);
pendingRefresh.set(false);
},
ModalityState.NON_MODAL);
}
}
/**
* Tests the StorageWriter in a Scenario where the Storage component throws data corruption exceptions (i.e., badOffset,
* and after reconciliation, the data is still corrupt).
*/
@Test
public void testWithStorageCorruptionErrors() throws Exception {
AtomicBoolean corruptionHappened = new AtomicBoolean();
Function<TestContext, ErrorInjector<Exception>> createErrorInjector = context -> {
byte[] corruptionData = "foo".getBytes();
SegmentHandle corruptedSegmentHandle = InMemoryStorage.newHandle(context.metadata.getStreamSegmentMetadata(0).getName(), false);
Supplier<Exception> exceptionSupplier = () -> {
// Corrupt data. We use an internal method (append) to atomically write data at the end of the segment.
// GetLength+Write would not work well because there may be concurrent writes that modify the data between
// requesting the length and attempting to write, thus causing the corruption to fail.
// NOTE: this is a synchronous call, but append() is also a sync method. If append() would become async,
// care must be taken not to block a thread while waiting for it.
context.storage.append(corruptedSegmentHandle, new ByteArrayInputStream(corruptionData), corruptionData.length);
// Return some other kind of exception.
return new TimeoutException("Intentional");
};
return new ErrorInjector<>(c -> !corruptionHappened.getAndSet(true), exceptionSupplier);
};
testWithStorageCriticalErrors(createErrorInjector, ex -> ex instanceof ReconciliationFailureException);
}
@Test
public void once_onlyCalledOnce() {
AtomicBoolean invoked = new AtomicBoolean();
Command action = () -> {
boolean calledPreviously = invoked.getAndSet(true);
Assert.assertFalse("Command should not invoked previously",
calledPreviously);
};
Registration registration = Registration.once(action);
Assert.assertFalse("Command should not yet be invoked", invoked.get());
registration.remove();
Assert.assertTrue("Command should be invoked", invoked.get());
// Action will throw if invoked again
registration.remove();
}
@Test
public void testRequestMessage() throws RemotingException, RequestTimeoutException, MQClientException, InterruptedException, MQBrokerException {
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
final AtomicBoolean finish = new AtomicBoolean(false);
new Thread(new Runnable() {
@Override public void run() {
ConcurrentHashMap<String, RequestResponseFuture> responseMap = RequestFutureTable.getRequestFutureTable();
assertThat(responseMap).isNotNull();
while (!finish.get()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
for (Map.Entry<String, RequestResponseFuture> entry : responseMap.entrySet()) {
RequestResponseFuture future = entry.getValue();
future.putResponseMessage(message);
}
}
}
}).start();
Message result = producer.request(message, 3 * 1000L);
finish.getAndSet(true);
assertThat(result.getTopic()).isEqualTo("FooBar");
assertThat(result.getBody()).isEqualTo(new byte[] {'a'});
}
/**
* Wrap the request.
* @param req Request
* @return New request
*/
private static Request wrap(final Request req) {
final AtomicBoolean seen = new AtomicBoolean(false);
return new RequestOf(
req::head,
() -> {
if (!seen.getAndSet(true)) {
throw new IllegalStateException(
"It's not allowed to call body() more than once"
);
}
return req.body();
}
);
}
private void releaseStutterLock(AtomicBoolean stutterLockIsNotified) {
if (!idbStutterTimeout.isPresent()) {
return;
}
if (!stutterLockIsNotified.getAndSet(true)) {
stutterLock.release();
}
}
private void releaseStutterLock(AtomicBoolean stutterLockIsNotified) {
if (!xctoolStutterTimeout.isPresent()) {
return;
}
if (!stutterLockIsNotified.getAndSet(true)) {
stutterLock.release();
}
}
@Test
public void submitRunnableSupplier() throws Throwable {
Task submitted1 = new Task();
Task submitted2 = new Task();
AtomicBoolean returnedSubmitted1 = new AtomicBoolean();
Supplier<Runnable> runnableSupplier = () -> returnedSubmitted1.getAndSet(true) ? submitted2 : submitted1;
executor.submitRunnable(runnableSupplier).toFuture().get();
submitted1.awaitDone();
executor.submitRunnable(runnableSupplier).toFuture().get();
submitted2.awaitDone();
}
@Override
public <T> ScheduledCompletableFuture<T> before(CompletableFuture<T> promise, Duration timeout) {
final AtomicBoolean done = new AtomicBoolean();
final Consumer<Runnable> runOnce = runnable -> {
if (!done.getAndSet(true)) {
runnable.run();
}
};
final ScheduledCompletableFutureOnce<T> wrappedPromise = new ScheduledCompletableFutureOnce<>();
Callable<T> callable = () -> {
wrappedPromise.completeExceptionally(new TimeoutException());
return null;
};
final ScheduledCompletableFutureOnce<T> afterPromise = afterInternal(wrappedPromise, callable, timeout);
wrappedPromise.exceptionally(e -> {
if (e instanceof CancellationException) {
// Also cancel the scheduled timer if returned completable future is cancelled.
afterPromise.cancel(true);
}
return null;
});
promise.thenAccept(p -> runOnce.accept(() -> wrappedPromise.complete(p))) //
.exceptionally(ex -> {
runOnce.accept(() -> wrappedPromise.completeExceptionally(ex));
return null;
});
return wrappedPromise;
}
public static void main(String[] args) {
AtomicBoolean atomicBoolean = new AtomicBoolean();
atomicBoolean.getAndSet(true);
AtomicLong atomicLong = new AtomicLong();
atomicLong.getAndDecrement();
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();
}
@Override
public <T> ScheduledCompletableFuture<T> before(CompletableFuture<T> promise, Duration timeout) {
final AtomicBoolean done = new AtomicBoolean();
final Consumer<Runnable> runOnce = runnable -> {
if (!done.getAndSet(true)) {
runnable.run();
}
};
final ScheduledCompletableFutureOnce<T> wrappedPromise = new ScheduledCompletableFutureOnce<>();
Callable<T> callable = () -> {
wrappedPromise.completeExceptionally(new TimeoutException());
return null;
};
final ScheduledCompletableFutureOnce<T> afterPromise = afterInternal(wrappedPromise, callable, timeout);
wrappedPromise.exceptionally(e -> {
if (e instanceof CancellationException) {
// Also cancel the scheduled timer if returned completable future is cancelled.
afterPromise.cancel(true);
}
return null;
});
promise.thenAccept(p -> runOnce.accept(() -> wrappedPromise.complete(p))) //
.exceptionally(ex -> {
runOnce.accept(() -> wrappedPromise.completeExceptionally(ex));
return null;
});
return wrappedPromise;
}
private void correctiveScrolling(int i, AtomicBoolean marker) {
final float floaterY = floatingsnooze.getTop();
if (marker.getAndSet(true)) return; // already processed
int val = 0;
int ii = 0;
while (val > -1) {
View v = recyclerView.getChildAt(ii);
if (v != null) {
val = recyclerView.getChildAdapterPosition(v);
if (val == i) {
final float lowest_point = v.getY() + (v.getHeight() * 2);
//Log.d(TAG, "Requested Child at position : " + i + " / " + ii + " " + val + " v:" + lowest_point + " vs " + floaterY);
if (lowest_point > floaterY) {
// is obscured
final float difference = lowest_point - floaterY;
// int scrollto = i+((int)difference)+1;
Log.d(TAG, "Corrective Scrolling by: " + (int) difference);
// TODO wrap with speed adjustment
recyclerView.smoothScrollBy(0, (int) difference);
}
val = -1;
}
} else {
val = -1;
}
ii++;
}
}
private void initOtherComponents() {
timer = new Timer(1000, e -> {
int remaining = NumberUtils.toInt(labelCountdownValue.getText(), (Integer) spinnerCountdownTime.getValue());
if (remaining <= 1) {
countdownEnds();
resetCountdown();
} else {
--remaining;
labelCountdownValue.setText(String.valueOf(remaining));
progressBarCountdown.setValue(progressBarCountdown.getMaximum() - remaining);
}
});
timer.setRepeats(true);
countdownSystemStarted = false;
nextBlack = new AtomicBoolean(Lizzie.board.getData().isBlackToPlay());
boardStateChangeObserver = new BoardStateChangeObserver() {
@Override
public void mainStreamAppended(BoardHistoryNode newNodeBegin, BoardHistoryNode head) {
}
@Override
public void mainStreamCut(BoardHistoryNode nodeBeforeCutPoint, BoardHistoryNode head) {
}
@Override
public void headMoved(BoardHistoryNode oldHead, BoardHistoryNode newHead) {
boolean newState = newHead.getData().isBlackToPlay();
boolean originalState = nextBlack.getAndSet(newState);
if (newState != originalState) {
boardPlayerChanged();
}
}
@Override
public void boardCleared(BoardHistoryNode initialNode, BoardHistoryNode initialHead) {
nextBlack.set(true);
boardPlayerChanged();
}
};
Lizzie.board.registerBoardStateChangeObserver(boardStateChangeObserver);
spinnerCountdownTime.setValue(Lizzie.optionSetting.getByoYomiSetting().getByoYomiTime());
labelCountdownValue.setText(String.valueOf(spinnerCountdownTime.getValue()));
checkBoxStopThinkingWhenCountDown.setSelected(Lizzie.optionSetting.getByoYomiSetting().isStopThinkingWhenCountingDown());
getRootPane().registerKeyboardAction(e -> dispatchEvent(new WindowEvent(ByoYomiAutoPlayDialog.this, WindowEvent.WINDOW_CLOSING)),
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
getRootPane().registerKeyboardAction(e -> dispatchEvent(new WindowEvent(ByoYomiAutoPlayDialog.this, WindowEvent.WINDOW_CLOSING)),
KeyStroke.getKeyStroke(KeyEvent.VK_B, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
@CheckForNull
private static Map<OffsetRange, ColoringAttributes> calculateOccurences(
@NonNull final ParserResult result,
final int caretPosition,
boolean includeQuotes,
@NonNull final AtomicBoolean cancelled) {
if (cancelled.getAndSet(false)) {
return null;
}
TokenHierarchy<?> th = result.getSnapshot().getTokenHierarchy();
if (th == null) {
return null;
}
TokenSequence<JsTokenId> ts = th.tokenSequence(JsTokenId.jsonLanguage());
if (ts == null) {
return null;
}
int offset = result.getSnapshot().getEmbeddedOffset(caretPosition);
int delta = ts.move(offset);
if (!ts.moveNext() && !ts.movePrevious()){
return null;
}
final Model model = Model.getModel(result, false);
if (model == null) {
return null;
}
Token<? extends JsTokenId> token = ts.token();
JsTokenId tokenId = token.id();
if (tokenId != JsTokenId.STRING && delta == 0 && ts.movePrevious()) {
token = ts.token();
tokenId = token.id();
}
ts.movePrevious();
final Token<? extends JsTokenId> prevToken = LexUtilities.findPreviousNonWsNonComment(ts);
final JsTokenId prevTokenId = prevToken.id();
Set<OffsetRange> ranges = new HashSet<>();
if (tokenId == JsTokenId.STRING && (prevTokenId == JsTokenId.BRACKET_LEFT_CURLY || prevTokenId == JsTokenId.OPERATOR_COMMA)) {
CharSequence text = token.text();
findRanges(model.getGlobalObject(), text.subSequence(1, text.length() - 1).toString(), includeQuotes, ranges);
}
final Map<OffsetRange, ColoringAttributes> res = new HashMap<>();
if (cancelled.getAndSet(false)) {
return null;
}
for (OffsetRange offsetRange : ranges) {
res.put(ModelUtils.documentOffsetRange(result, offsetRange.getStart(), offsetRange.getEnd()), ColoringAttributes.MARK_OCCURRENCES);
}
return res;
}
@Test
public void testErrorListener() throws Exception
{
//The first call to the ACL provider will return a reasonable
//value. The second will throw an error. This is because the ACL
//provider is accessed prior to the backgrounding call.
final AtomicBoolean aclProviderCalled = new AtomicBoolean(false);
ACLProvider badAclProvider = new ACLProvider()
{
@Override
public List<ACL> getDefaultAcl()
{
if(aclProviderCalled.getAndSet(true))
{
throw new UnsupportedOperationException();
}
else
{
return new ArrayList<>();
}
}
@Override
public List<ACL> getAclForPath(String path)
{
if(aclProviderCalled.getAndSet(true))
{
throw new UnsupportedOperationException();
}
else
{
return new ArrayList<>();
}
}
};
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(server.getConnectString())
.retryPolicy(new RetryOneTime(1))
.aclProvider(badAclProvider)
.build();
try
{
client.start();
final CountDownLatch errorLatch = new CountDownLatch(1);
UnhandledErrorListener listener = new UnhandledErrorListener()
{
@Override
public void unhandledError(String message, Throwable e)
{
if ( e instanceof UnsupportedOperationException )
{
errorLatch.countDown();
}
}
};
client.create().inBackground().withUnhandledErrorListener(listener).forPath("/foo");
Assert.assertTrue(new Timing().awaitLatch(errorLatch));
}
finally
{
CloseableUtils.closeQuietly(client);
}
}
@Test
public void testCheckCannotBeInterrupted() throws Exception {
final Thread mainThread = Thread.currentThread();
final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
final AtomicBoolean sentInterrupt = new AtomicBoolean(false);
Predicate<Path> interrupterPredicate = new Predicate<Path>() {
@Override
public boolean apply(Path input) {
if (!sentInterrupt.getAndSet(true)) {
mainThread.interrupt();
}
return true;
}
};
List<Path> result =
new UnixGlob.Builder(tmpPath)
.addPatterns("**", "*")
.setDirectoryFilter(interrupterPredicate)
.setExecutor(executor)
.glob();
// In the non-interruptible case, the interrupt bit should be set, but the
// glob should return the correct set of full results.
assertThat(Thread.interrupted()).isTrue();
assertThat(result)
.containsExactlyElementsIn(
resolvePaths(
".",
"foo",
"foo/bar",
"foo/bar/wiz",
"foo/bar/wiz/file",
"foo/barnacle",
"foo/barnacle/wiz",
"food",
"food/barnacle",
"food/barnacle/wiz",
"fool",
"fool/barnacle",
"fool/barnacle/wiz"));
assertThat(executor.isShutdown()).isFalse();
executor.shutdown();
assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
.isTrue();
}
/** sets the atomic reference to the given value, and returns whether there is any change */
public static boolean setIfDifferent(AtomicBoolean ref, boolean value) {
return ref.getAndSet(value) != value;
}
@Test
public void testErrorListener() throws Exception
{
//The first call to the ACL provider will return a reasonable
//value. The second will throw an error. This is because the ACL
//provider is accessed prior to the backgrounding call.
final AtomicBoolean aclProviderCalled = new AtomicBoolean(false);
ACLProvider badAclProvider = new ACLProvider()
{
@Override
public List<ACL> getDefaultAcl()
{
if(aclProviderCalled.getAndSet(true))
{
throw new UnsupportedOperationException();
}
else
{
return new ArrayList<>();
}
}
@Override
public List<ACL> getAclForPath(String path)
{
if(aclProviderCalled.getAndSet(true))
{
throw new UnsupportedOperationException();
}
else
{
return new ArrayList<>();
}
}
};
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(server.getConnectString())
.retryPolicy(new RetryOneTime(1))
.aclProvider(badAclProvider)
.build();
try
{
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
final CountDownLatch errorLatch = new CountDownLatch(1);
UnhandledErrorListener listener = (message, e) -> {
if ( e instanceof UnsupportedOperationException )
{
errorLatch.countDown();
}
};
async.with(listener).create().forPath("/foo");
Assert.assertTrue(new Timing().awaitLatch(errorLatch));
}
finally
{
CloseableUtils.closeQuietly(client);
}
}
@Test(timeout = 10000)
public void testExceptionSealedCallback() throws Exception {
UUID cid = UUID.randomUUID();
PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
implementAsDirectExecutor(executor); // Ensure task submitted to executor is run inline.
cf.setExecutor(executor);
MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
ClientConnection connection = mock(ClientConnection.class);
cf.provideConnection(uri, connection);
AtomicBoolean shouldThrow = new AtomicBoolean(true);
// call back which throws an exception.
Consumer<Segment> exceptionCallback = s -> {
if (shouldThrow.getAndSet(false)) {
throw new IllegalStateException();
}
};
SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, exceptionCallback,
RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
output.reconnect();
verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
ByteBuffer data = getBuffer("test");
CompletableFuture<Void> ack = new CompletableFuture<>();
output.write(PendingEvent.withoutHeader(null, data, ack));
assertEquals(false, ack.isDone());
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
return null;
}
}).when(connection).send(new SetupAppend(3, cid, SEGMENT, ""));
AssertExtensions.assertBlocks(() -> {
AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
}, () -> {
cf.getProcessor(uri).segmentIsSealed(new WireCommands.SegmentIsSealed(output.getRequestId(), SEGMENT, "SomeException", 1));
output.getUnackedEventsOnSeal();
});
verify(connection).send(new WireCommands.KeepAlive());
verify(connection).send(new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
assertEquals(false, ack.isDone());
}