下面列出了怎么用java.util.concurrent.atomic.AtomicBoolean的API类实例代码及写法,或者点击链接到github查看源代码。
@UiThreadTest
@SmallTest
public void testListenerGarbageCollected() throws Exception {
final AtomicBoolean called = new AtomicBoolean();
uut.registerIntChangeListener(new OnPreferenceValueChangedListener<Integer>() {
@Override
public void onChanged(Integer newValue) {
called.set(true);
}
});
// nasty, but it does force collection of soft references...
// TODO is there a better way to do this?
try {
Object[] ignored = new Object[(int) Runtime.getRuntime().maxMemory()];
} catch (OutOfMemoryError e) {
// NOP
}
uut.setInt(1);
assertFalse(called.get());
}
/**
* Writes the results of a {@link QueryResultStream} to the output stream as NTriples until the
* shutdown signal is set.
*
* @param out - The stream the NTriples data will be written to. (not null)
* @param resultsStream - The results stream that will be polled for results to
* write to {@code out}. (not null)
* @param shutdownSignal - Setting this signal will cause the thread that
* is processing this function to finish and leave. (not null)
* @throws RDFHandlerException A problem was encountered while
* writing the NTriples to the output stream.
* @throws IllegalStateException The {@code resultsStream} is closed.
* @throws RyaStreamsException Could not fetch the next set of results.
*/
public static void toNtriplesFile(
final OutputStream out,
final QueryResultStream<VisibilityStatement> resultsStream,
final AtomicBoolean shutdownSignal) throws RDFHandlerException, IllegalStateException, RyaStreamsException {
requireNonNull(out);
requireNonNull(resultsStream);
requireNonNull(shutdownSignal);
final RDFWriter writer = Rio.createWriter(RDFFormat.NTRIPLES, out);
writer.startRDF();
while(!shutdownSignal.get()) {
final Iterable<VisibilityStatement> it = resultsStream.poll(1000);
for(final VisibilityStatement result : it) {
writer.handleStatement(result);
}
}
writer.endRDF();
}
/**
* Tests session state change callbacks.
*/
public void testSessionStateChange() {
ClientSessionState state = new ClientSessionState(UUID.randomUUID().toString());
AtomicBoolean changed = new AtomicBoolean();
AtomicReference<Session.State> change = new AtomicReference<>();
Listener<Session.State> listener = state.onStateChange(s -> {
changed.set(true);
change.set(s);
});
assertEquals(state.getState(), Session.State.CLOSED);
state.setState(Session.State.CLOSED);
assertFalse(changed.get());
state.setState(Session.State.OPEN);
assertTrue(changed.get());
assertEquals(change.get(), Session.State.OPEN);
changed.set(false);
listener.close();
state.setState(Session.State.EXPIRED);
assertFalse(changed.get());
}
public CathInstallation(String cacheLocation, boolean usingCDDF, boolean parseCF) {
setCacheLocation(cacheLocation);
useCathDomainDescriptionFile = usingCDDF;
parseCathFragments = parseCF;
installedDomainDescription = new AtomicBoolean(false);
installedDomainList = new AtomicBoolean(false);
installedNodeList = new AtomicBoolean(false);
installedDomall = new AtomicBoolean(false);
cathVersion = DEFAULT_VERSION;
cathDownloadUrl = CATH_DOWNLOAD_URL;
pdbMap = new HashMap<String, List<CathDomain>>();
domainMap = new HashMap<String ,CathDomain>();
cathTree = new HashMap<String, CathNode>();
if (parseCathFragments) fragmentMap = new HashMap<String,List<CathFragment>>();
}
@Test(timeout=5000L)
public void toStringDoesntResolveLazyFuture() throws Exception {
String imageName = Base58.randomString(8).toLowerCase();
AtomicBoolean resolved = new AtomicBoolean(false);
Future<String> imageNameFuture = new LazyFuture<String>() {
@Override
protected String resolve() {
resolved.set(true);
return imageName;
}
};
// verify that we've set up the test properly
assertFalse(imageNameFuture.isDone());
RemoteDockerImage remoteDockerImage = new RemoteDockerImage(imageNameFuture);
assertThat(remoteDockerImage.toString(), containsString("imageName=<resolving>"));
// Make sure the act of calling toString doesn't resolve the imageNameFuture
assertFalse(imageNameFuture.isDone());
assertFalse(resolved.get());
// Trigger resolve
imageNameFuture.get();
assertThat(remoteDockerImage.toString(), containsString("imageName=" + imageName));
}
@Test
void shouldPropagateRetryToEveryListener() {
final AtomicBoolean success = new AtomicBoolean(false);
final RequestArguments arguments = RequestArguments.create();
final IllegalStateException exception = new IllegalStateException();
Failsafe.with(new RetryPolicy<ClientHttpResponse>()
.withMaxRetries(3)
.onRetry(new RetryRequestPolicy.RetryListenerAdapter(unit, arguments)))
.run(() -> {
if (!success.getAndSet(true)) {
throw exception;
}
});
verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
verify(first).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastResult, nullValue())));
verify(second).onRetry(eq(arguments), argThat(hasFeature(ExecutionAttemptedEvent::getLastFailure, notNullValue())));
}
public TestReader(String name,
DistributedLogManager dlm,
DLSN startDLSN,
boolean simulateErrors,
int delayMs,
CountDownLatch readyLatch,
CountDownLatch countLatch,
CountDownLatch completionLatch) {
this.readerName = name;
this.dlm = dlm;
this.startDLSN = startDLSN;
this.simulateErrors = simulateErrors;
this.delayMs = delayMs;
this.readyLatch = readyLatch;
this.countLatch = countLatch;
this.completionLatch = completionLatch;
// States
this.errorsFound = new AtomicBoolean(false);
this.readCount = new AtomicInteger(0);
this.positionReaderCount = new AtomicInteger(0);
// Executors
this.executorService = Executors.newSingleThreadScheduledExecutor();
}
@Override
public void open() {
if ( SwingUtilities.isEventDispatchThread()){
final AtomicBoolean cancel = new AtomicBoolean();
ProgressUtils.runOffEventDispatchThread(new Runnable() {
@Override
public void run() {
doOpen();
}
},
NbBundle.getMessage(OpenCookieFactory.class, "TXT_OpenResource"), // NOI18N
cancel,
false);
}
else {
doOpen();
}
}
@Test
public void testTriggerSavepointRetry() throws Exception {
final TriggerId triggerId = new TriggerId();
final String expectedSavepointDir = "hello";
final AtomicBoolean failRequest = new AtomicBoolean(true);
try (final RestServerEndpoint restServerEndpoint = createRestServerEndpoint(
request -> triggerId,
trigger -> {
if (failRequest.compareAndSet(true, false)) {
throw new RestHandlerException("expected", HttpResponseStatus.SERVICE_UNAVAILABLE);
} else {
return new SavepointInfo(expectedSavepointDir, null);
}
})) {
final RestClusterClient<?> restClusterClient = createRestClusterClient(restServerEndpoint.getServerAddress().getPort());
final String savepointPath = restClusterClient.triggerSavepoint(new JobID(), null).get();
assertEquals(expectedSavepointDir, savepointPath);
}
}
private static Future<?> monitor(InputStream input,
Predicate<String> filter,
Function<String, String> transform,
Consumer<String> output,
AtomicBoolean running) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
return EXECUTOR.submit(() -> {
while (running.get()) {
reader.lines().forEach(line -> {
if (filter.test(line)) {
output.accept(transform.apply(line));
}
});
}
});
}
/**
* Test of nextEvent method, of class LinuxNotifier.
*
* @throws java.lang.Exception
*/
public void testNextEvent() throws Exception {
prepareFiles();
final AtomicBoolean folder2refreshed = new AtomicBoolean(false);
Logger log = Logger.getLogger(FolderObj.class.getName());
Handler h = createHandler(folder2refreshed);
log.addHandler(h);
try {
FileChangeListener l = new FileChangeAdapter();
FileUtil.addFileChangeListener(l, folder1text1Txt);
// This causes an IN_IGNORED native event.
FileUtil.removeFileChangeListener(l, folder1text1Txt);
// Native listeners may need some time.
Thread.sleep(2000);
} finally {
log.removeHandler(h);
}
assertFalse("Folder folder2 should not be refreshed.",
folder2refreshed.get());
}
@Override
public void getJobBuildResult(HudsonJobBuild build, AtomicBoolean building, AtomicReference<Result> result) {
Document doc = getDocument(build.getUrl() + XML_API_URL +
"?xpath=/*/*[name()='result'%20or%20name()='building']&wrapper=root", true);
if (doc == null) {
return;
}
Element docEl = doc.getDocumentElement();
Element resultEl = XMLUtil.findElement(docEl, "result", null);
if (resultEl != null) {
result.set(Result.valueOf(XMLUtil.findText(resultEl)));
}
Element buildingEl = XMLUtil.findElement(docEl, "building", null);
if (buildingEl != null) {
building.set(Boolean.parseBoolean(XMLUtil.findText(buildingEl)));
}
}
@Test
public void eventsFromEffectHandlerDuringDisposeAreIgnored() throws Exception {
// Events emitted by the effect handler during dispose should be ignored.
AtomicBoolean updateWasCalled = new AtomicBoolean();
final MobiusLoop.Builder<String, TestEvent, TestEffect> builder =
Mobius.loop(
(model, event) -> {
updateWasCalled.set(true);
return Next.noChange();
},
new EmitDuringDisposeEffectHandler());
builder.startFrom("foo").dispose();
assertFalse(updateWasCalled.get());
}
private PlanTraversal.Callback getFlatAlternativeCallback(AtomicBoolean testOutcome) {
return (operator, fromInputSlot, fromOutputSlot) -> {
if (operator.isAlternative()) {
final OperatorAlternative operatorAlternative = (OperatorAlternative) operator;
for (OperatorAlternative.Alternative alternative : operatorAlternative.getAlternatives()) {
final Collection<Operator> containedOperators = alternative.getContainedOperators();
if (containedOperators.size() == 1) {
Operator containedOperator = RheemCollections.getSingle(containedOperators);
if (containedOperator.isAlternative()) {
this.logger.warn("Improper alternative {}: contains alternatives.", alternative);
testOutcome.set(false);
}
} else {
// We could check if there are singleton Subplans with an OperatorAlternative embedded,
// but this would violate the singleton Subplan rule anyway.
alternative.traverse(this.getFlatAlternativeCallback(testOutcome));
}
}
}
};
}
@Test
public void errorResourcePublisherAfterEmitIsDropped() {
AtomicBoolean commitDone = new AtomicBoolean();
AtomicBoolean rollbackDone = new AtomicBoolean();
TestPublisher<String> testPublisher = TestPublisher.createCold();
testPublisher.next("Resource").error(new IllegalStateException("boom"));
Flux<String> test = Flux.usingWhen(testPublisher,
Mono::just,
tr -> Mono.fromRunnable(() -> commitDone.set(true)),
(tr, err) -> Mono.fromRunnable(() -> rollbackDone.set(true)),
tr -> Mono.fromRunnable(() -> rollbackDone.set(true)));
StepVerifier.create(test)
.expectNext("Resource")
.expectComplete()
.verifyThenAssertThat(Duration.ofSeconds(2))
.hasDroppedErrorWithMessage("boom")
.hasNotDroppedElements();
assertThat(commitDone).isTrue();
assertThat(rollbackDone).isFalse();
testPublisher.assertCancelled();
}
@Test
public void testChangingHashPartitioner() {
cpConfig.setLoadBalancingStrategy(LoadBalancingStrategy.TokenAware);
cpConfig.withTokenSupplier(getTokenMapSupplier());
cpConfig.withHashPartitioner(getMockHashPartitioner(1000000000L));
HostSelectionWithFallback<Integer> selection = new HostSelectionWithFallback<Integer>(cpConfig, cpMonitor);
Map<Host, HostConnectionPool<Integer>> pools = new HashMap<Host, HostConnectionPool<Integer>>();
for (Host host : hosts) {
poolStatus.put(host, new AtomicBoolean(true));
pools.put(host, getMockHostConnectionPool(host, poolStatus.get(host)));
}
selection.initWithHosts(pools);
Connection<Integer> connection = selection.getConnection(testOperation, 10, TimeUnit.MILLISECONDS);
// Verify that h1 has been selected instead of h2
assertEquals("h1", connection.getHost().getHostAddress());
}
public ClusterTopicManipulationService(String name, AdminClient adminClient) {
LOGGER.info("ClusterTopicManipulationService constructor initiated {}", this.getClass().getName());
_isOngoingTopicCreationDone = true;
_isOngoingTopicDeletionDone = true;
_adminClient = adminClient;
_executor = Executors.newSingleThreadScheduledExecutor();
_reportIntervalSecond = Duration.ofSeconds(1);
_running = new AtomicBoolean(false);
_configDefinedServiceName = name;
// TODO: instantiate a new instance of ClusterTopicManipulationMetrics(..) here.
MetricConfig metricConfig = new MetricConfig().samples(60).timeWindow(1000, TimeUnit.MILLISECONDS);
List<MetricsReporter> reporters = new ArrayList<>();
reporters.add(new JmxReporter(Service.JMX_PREFIX));
Metrics metrics = new Metrics(metricConfig, reporters, new SystemTime());
Map<String, String> tags = new HashMap<>();
tags.put("name", name);
_clusterTopicManipulationMetrics = new ClusterTopicManipulationMetrics(metrics, tags);
}
private boolean waitIfPaused() {
AtomicBoolean pause = this.engine.getPause();
if (pause.get()) {
synchronized (this.engine.getPauseLock()) {
if (pause.get()) {
L.d(LOG_WAITING_FOR_RESUME, this.memoryCacheKey);
try {
this.engine.getPauseLock().wait();
L.d(LOG_RESUME_AFTER_PAUSE, this.memoryCacheKey);
} catch (InterruptedException e) {
L.e(LOG_TASK_INTERRUPTED, this.memoryCacheKey);
return true;
}
}
}
}
return isTaskNotActual();
}
@Test(timeout = 10_000)
public void testReadBuffer() throws InterruptedException, IOException {
AtomicBoolean atb = new AtomicBoolean(true);
TaskInbound ti =
new TaskInbound(p2pLOG, surveyLog, p2pMgr, selector, atb, nodeMgr, hldrMap, rhs1, msgInQue);
assertNotNull(ti);
// settings for readBuffer
when(sk.channel()).thenReturn(sc);
when(sc.read(any(ByteBuffer.class))).thenReturn(0);
// settings for run
when(sk.isValid()).thenReturn(true);
when(sk.isReadable()).thenReturn(true);
when(sk.attachment()).thenReturn(cb);
when(selector.selectNow()).thenReturn(1);
Set<SelectionKey> ss = new LinkedHashSet<>();
ss.add(sk);
when(selector.selectedKeys()).thenReturn(ss);
// execute the task
Thread t = new Thread(ti);
t.start();
assertTrue(t.isAlive());
Thread.sleep(100);
atb.set(false);
while (!t.getState().toString().contains("TERMINATED")) {
Thread.sleep(10);
}
}
@Test(timeout = 1000)
public void testRestartingScheduler() throws Exception {
final TimeoutScheduler scheduler = TimeoutScheduler.newInstance();
final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
scheduler.setGracePeriod(grace);
Assert.assertFalse(scheduler.hasScheduler());
final ErrorHandler errorHandler = new ErrorHandler();
for(int i = 0; i < 2; i++) {
final AtomicBoolean fired = new AtomicBoolean(false);
scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> {
Assert.assertFalse(fired.get());
fired.set(true);
}, errorHandler);
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertFalse(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertTrue(scheduler.hasScheduler());
Thread.sleep(100);
Assert.assertTrue(fired.get());
Assert.assertFalse(scheduler.hasScheduler());
}
errorHandler.assertNoError();
}
@Before
public void addData() {
partitionMessagePool = new PartitionMessagePool(TestTalosStormConfig.getConfig());
addDataFinished = new AtomicBoolean(false);
new Thread(new Runnable() {
@Override
public void run() {
for (TalosStormMessage m : input) {
partitionMessagePool.put(m);
}
addDataFinished.set(true);
}
}).start();
}
/**
* @throws Exception if failed.
*/
@Test
public void testMultiThreaded() throws Exception {
Ignite ignite = G.ignite(getTestIgniteInstanceName());
ignite.compute().localDeployTask(GridTaskSessionTestTask.class, GridTaskSessionTestTask.class.getClassLoader());
final GridThreadSerialNumber sNum = new GridThreadSerialNumber();
final AtomicBoolean failed = new AtomicBoolean(false);
GridTestUtils.runMultiThreaded(new Runnable() {
@Override public void run() {
int num = sNum.get();
try {
checkTask(num);
}
catch (Throwable e) {
error("Failed to execute task.", e);
failed.set(true);
}
}
}, EXEC_COUNT, "grid-session-test");
if (failed.get())
fail();
}
@Test
public void pairWiseZipIncremental() {
AtomicBoolean data = new AtomicBoolean(false);
AtomicReference<Vector<Tuple2<Integer,String>>> values = new AtomicReference<>(Vector.empty());
AtomicBoolean complete = new AtomicBoolean(false);
AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);
Subscription sub = of(1).zip(of("test"))
.zip(of("test2")).map(t -> Tuple.tuple(t._1()
._1(),
t._1()
._2() + t._2())).forEach(0, n -> {
data.set(true);
values.updateAndGet(v -> v.plus(n));
}, e -> {
error.set(e);
}, () -> {
complete.set(true);
});
assertFalse(data.get());
assertFalse(complete.get());
assertNull(error.get());
assertThat(values.get(), Matchers.equalTo(Vector.empty()));
sub.request(10l);
assertTrue(data.get());
assertTrue(complete.get());
assertNull(error.get());
assertThat(values.get(), Matchers.equalTo(Vector.of(Tuple.tuple(1,"testtest2"))));
}
@org.junit.Test
public void testBinaryWithByteArray() throws Exception {
final byte[] payload = "payload".getBytes();
final AtomicReference<Throwable> cause = new AtomicReference<>();
final AtomicBoolean connected = new AtomicBoolean(false);
final CompletableFuture<?> latch = new CompletableFuture<>();
class TestEndPoint extends Endpoint {
@Override
public void onOpen(final Session session, EndpointConfig config) {
connected.set(true);
session.addMessageHandler(new MessageHandler.Whole<byte[]>() {
@Override
public void onMessage(byte[] message) {
session.getAsyncRemote().sendBinary(ByteBuffer.wrap(message.clone()));
}
});
}
}
ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false);
builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
deployServlet(builder);
WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
client.connect();
client.send(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(BinaryWebSocketFrame.class, payload, latch));
latch.get();
Assert.assertNull(cause.get());
client.destroy();
}
/**
* @param email Site account email
* @param password Site account password
*/
public NicoAudioSourceManager(String email, String password) {
this.email = email;
this.password = password;
httpInterfaceManager = HttpClientTools.createDefaultThreadLocalManager();
loggedIn = new AtomicBoolean();
}
public static void waitForConditionEx(final AtomicBoolean condition)
throws InterruptedException
{
synchronized (condition) {
while (!condition.get()) {
condition.wait();
}
}
}
public static void waitForConditionEx(final AtomicBoolean condition)
throws InterruptedException
{
synchronized (condition) {
while (!condition.get()) {
condition.wait();
}
}
}
@Test
public void estimateRemainingTaskCapacityResetWhenWorkerTaskIsDisposed()
throws InterruptedException {
BoundedElasticScheduler boundedElasticScheduler = afterTest.autoDispose(new BoundedElasticScheduler(1, 1, Thread::new, 10));
Worker worker = afterTest.autoDispose(boundedElasticScheduler.createWorker());
CountDownLatch latch = new CountDownLatch(1);
AtomicBoolean taskRan = new AtomicBoolean();
//occupy the scheduler
worker.schedule(() -> {
try {
latch.await();
}
catch (InterruptedException e) {
//expected to be interrupted
}
});
Thread.sleep(10); //small window to start the first task
//enqueue task on worker
Disposable task = worker.schedule(() -> taskRan.set(true));
assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity()).as("capacity when running").isZero();
task.dispose();
Awaitility.with().pollDelay(50, TimeUnit.MILLISECONDS)
.await().atMost(100, TimeUnit.MILLISECONDS)
.untilAsserted(() -> assertThat(boundedElasticScheduler.estimateRemainingTaskCapacity())
.as("capacity after dispose").isOne());
}
private static <T> void streamGetResult(PostgresClientStreamResult<T> result,
String element, HttpServerResponse response) {
response.setStatusCode(200);
response.setChunked(true);
response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response.write("{\n");
response.write(String.format(" \"%s\": [%n", element));
AtomicBoolean first = new AtomicBoolean(true);
result.exceptionHandler(res -> {
String message = res.getMessage();
List<Diagnostic> diag = new ArrayList<>();
diag.add(new Diagnostic().withCode("500").withMessage(message));
result.resultInto().setDiagnostics(diag);
streamTrailer(response, result.resultInto());
});
result.endHandler(res -> streamTrailer(response, result.resultInto()));
result.handler(res -> {
String itemString = null;
try {
itemString = OBJECT_MAPPER.writeValueAsString(res);
} catch (JsonProcessingException ex) {
logger.error(ex.getMessage(), ex);
throw new IllegalArgumentException(ex.getCause());
}
if (first.get()) {
first.set(false);
} else {
response.write(String.format(",%n"));
}
response.write(itemString);
});
}
@Test(timeout=10000)
public void demoParallel() throws Exception
{
final AtomicBoolean you_can_quit = new AtomicBoolean();
JobManager.schedule("A", monitor ->
{
while (! you_can_quit.get())
{
System.out.println("Job A");
Thread.sleep(1000);
}
});
JobManager.schedule("B", monitor ->
{
while (! you_can_quit.get())
{
System.out.println("Job B");
Thread.sleep(1000);
}
});
while (JobManager.getJobCount() < 2)
Thread.sleep(200);
you_can_quit.set(true);
while (JobManager.getJobCount() > 0)
Thread.sleep(200);
}