本文整理汇总了Java中java.util.concurrent.atomic.AtomicBoolean.compareAndSet方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicBoolean.compareAndSet方法的具体用法?Java AtomicBoolean.compareAndSet怎么用?Java AtomicBoolean.compareAndSet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.atomic.AtomicBoolean
的用法示例。
在下文中一共展示了AtomicBoolean.compareAndSet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addRoots
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public @Override boolean addRoots(final URL[] urls, SourceGroup grp, String type) throws IOException {
final AtomicBoolean added = new AtomicBoolean();
final String scope = findScope(grp, type);
ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
public @Override void performOperation(POMModel model) {
for (URL url : urls) {
File jar = FileUtil.archiveOrDirForURL(url);
if (jar != null && jar.isFile()) {
try {
added.compareAndSet(false, addRemoveJAR(jar, model, scope, true));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} else {
Logger.getLogger(CPExtender.class.getName()).log(Level.INFO, "Adding non-jar root to Maven projects makes no sense. ({0})", url); //NOI18N
}
}
}
};
FileObject pom = project.getProjectDirectory().getFileObject(POM_XML);//NOI18N
org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(pom, Collections.singletonList(operation));
if (added.get()) {
project.getLookup().lookup(NbMavenProject.class).triggerDependencyDownload();
}
return added.get();
}
示例2: testPrimaryReference
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public void testPrimaryReference() throws Exception {
final IndexShard shard = mock(IndexShard.class);
final long primaryTerm = 1 + randomInt(200);
when(shard.getPrimaryTerm()).thenReturn(primaryTerm);
AtomicBoolean closed = new AtomicBoolean();
Releasable releasable = () -> {
if (closed.compareAndSet(false, true) == false) {
fail("releasable is closed twice");
}
};
TestAction.PrimaryShardReference primary = action.new PrimaryShardReference(shard, releasable);
final Request request = new Request();
Request replicaRequest = (Request) primary.perform(request).replicaRequest;
assertThat(replicaRequest.primaryTerm(), equalTo(primaryTerm));
final ElasticsearchException exception = new ElasticsearchException("testing");
primary.failShard("test", exception);
verify(shard).failShard("test", exception);
primary.close();
assertTrue(closed.get());
}
示例3: tAtomicBoolean
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public void tAtomicBoolean() {
System.currentTimeMillis();
AtomicBoolean atomic = new AtomicBoolean();
long t1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
if (atomic.compareAndSet(false, true)) {
try {
// ...
} finally {
atomic.set(false);
}
}
}
long t2 = System.currentTimeMillis();
System.out.println("take time:" + (t2 - t1) + " ms.");
}
示例4: testCacheInvalidation
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的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: send
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
/**
* Send back the result
* @param ctx channel context
* @param result rpc result
*/
private void send(ChannelHandlerContext ctx, Object result) {
int seqId = 0;
Channel ch = ctx.channel();
try {
seqId = ((ByteBuf) result).readInt();
((ByteBuf) result).resetReaderIndex();
AtomicBoolean channelInUse = channelStates.get(ctx);
if (channelInUse == null) {
return;
}
long startTs = System.currentTimeMillis();
while (true) {
if (channelInUse.compareAndSet(false, true)) {
ctx.writeAndFlush(result);
channelInUse.set(false);
LOG.debug(
"send response buf=" + result + ",channel ctx=" + ctx.channel() + ", seqId=" + seqId
+ " use time=" + (System.currentTimeMillis() - startTs));
return;
}
Thread.sleep(10);
}
} catch (Throwable ex) {
LOG.error("send response of request failed, request seqId=" + seqId + ", channel=" + ch, ex);
}
}
示例6: updateCurrentlyServingReplica
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
private void updateCurrentlyServingReplica(ScannerCallable scanner, Result[] result,
AtomicBoolean done, ExecutorService pool) {
if (done.compareAndSet(false, true)) {
if (currentScannerCallable != scanner) replicaSwitched.set(true);
currentScannerCallable = scanner;
// store where to start the replica scanner from if we need to.
if (result != null && result.length != 0) this.lastResult = result[result.length - 1];
if (LOG.isTraceEnabled()) {
LOG.trace("Setting current scanner as id=" + currentScannerCallable.scannerId +
" associated with replica=" + currentScannerCallable.getHRegionInfo().getReplicaId());
}
// close all outstanding replica scanners but the one we heard back from
outstandingCallables.remove(scanner);
for (ScannerCallable s : outstandingCallables) {
if (LOG.isTraceEnabled()) {
LOG.trace("Closing scanner id=" + s.scannerId +
", replica=" + s.getHRegionInfo().getRegionId() +
" because slow and replica=" +
this.currentScannerCallable.getHRegionInfo().getReplicaId() + " succeeded");
}
// Submit the "close" to the pool since this might take time, and we don't
// want to wait for the "close" to happen yet. The "wait" will happen when
// the table is closed (when the awaitTermination of the underlying pool is called)
s.setClose();
final RetryingRPC r = new RetryingRPC(s);
pool.submit(new Callable<Void>(){
@Override
public Void call() throws Exception {
r.call(scannerTimeout);
return null;
}
});
}
// now clear outstandingCallables since we scheduled a close for all the contained scanners
outstandingCallables.clear();
}
}
示例7: cancellable
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
/**
* Produces a token which may be passed to {@link AggregateProgressFactory#createHandle}
* in order to permit progress to be canceled.
* If an event is received after a cancel request has been made, {@link ThreadDeath} will
* be thrown (which you probably also want to catch and handle gracefully).
* Due to AETHER-95, {@link IllegalStateException} with a cause of {@link ThreadDeath} might also be thrown.
* Must be called by the same thread as will call {@link #setAggregateHandle} and runs the process.
* @return a cancellation token
*/
public static Cancellable cancellable() {
final AtomicBoolean b = new AtomicBoolean();
activeListener().cancel = b;
return new Cancellable() {
public @Override boolean cancel() {
return b.compareAndSet(false, true);
}
};
}
示例8: downloadProducts
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void downloadProducts() throws Exception {
doAnswer(invocation -> {
PublishSubject<Product> publishSubject = (PublishSubject<Product>) invocation.getArguments()[1];
publishSubject.onNext(Product.getDefaultInstance());
publishSubject.onComplete();
return null;
}).when(productDao).downloadProducts(any(), any());
List<Product> downloadedProducts = Lists.newArrayList();
AtomicBoolean onCompletedCalled = new AtomicBoolean(false);
StreamObserver<Product> downloadObserver = new StreamObserver<Product>() {
@Override
public void onNext(Product value) {
downloadedProducts.add(value);
}
@Override
public void onError(Throwable t) {
fail("should not fail");
}
@Override
public void onCompleted() {
onCompletedCalled.compareAndSet(false, true);
}
};
productReadService.downloadProducts(DownloadProductsRequest.getDefaultInstance(), downloadObserver);
verify(productDao, times(1)).downloadProducts(any(), any());
assertThat(downloadedProducts).containsOnly(Product.getDefaultInstance());
assertThat(onCompletedCalled).isTrue();
}
示例9: tryAcquire
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Nullable private Releasable tryAcquire() throws InterruptedException {
if (semaphore.tryAcquire(1, 0, TimeUnit.SECONDS)) { // the untimed tryAcquire methods do not honor the fairness setting
AtomicBoolean closed = new AtomicBoolean();
return () -> {
if (closed.compareAndSet(false, true)) {
semaphore.release(1);
}
};
}
return null;
}
示例10: wasOpenedHandlerCalled
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
boolean wasOpenedHandlerCalled(HRegionInfo hri) {
AtomicBoolean b = openedRegionHandlerCalled.get(hri);
//compareAndSet to be sure that unit tests don't see stale values. Means,
//we will return true exactly once unless the handler code resets to true
//this value.
return b == null ? false : b.compareAndSet(true, false);
}
示例11: init
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
protected void init(BufferedSource bufferedSource, final LogBean record, long timeout) {
this.timeout = timeout;
isFirstPacket = true;
replied = false;
isFinish = new AtomicBoolean(false);
runTimeOut = new Runnable() {
@Override
public void run() {
while (replied) {
replied = false;
try {
Thread.sleep(ProbeBufferedSource.this.timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (isFinish.compareAndSet(false, true)) {
if (!cancelSubmit) {
FileUtil.getInstance().addReportContent(record.toString());
}
}
}
};
this.source = bufferedSource;
this.record = record;
}
示例12: checkBuffer
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
private final boolean checkBuffer(final ByteBuffer bb, final boolean expect, final boolean update) {
synchronized (mapTrack) {
final AtomicBoolean inUse = mapTrack.get(bb);
if (inUse == null) {
return false;
}
return inUse.compareAndSet(expect, update);
}
}
示例13: testCompareAndSetInMultipleThreads
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
/**
* compareAndSet in one thread enables another waiting for value
* to succeed
*/
public void testCompareAndSetInMultipleThreads() throws Exception {
final AtomicBoolean ai = new AtomicBoolean(true);
Thread t = new Thread(new CheckedRunnable() {
public void realRun() {
while (!ai.compareAndSet(false, true)) Thread.yield();
}});
t.start();
assertTrue(ai.compareAndSet(true, false));
t.join(LONG_DELAY_MS);
assertFalse(t.isAlive());
}
示例14: asyncReloadDictionary
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
/**
* Reloads the dictionary. Access is controlled on a per dictionary file basis.
*/
private void asyncReloadDictionary() {
final AtomicBoolean isReloading = mIsReloading;
if (!isReloading.compareAndSet(false, true)) {
return;
}
final File dictFile = mDictFile;
asyncExecuteTaskWithWriteLock(new Runnable() {
@Override
public void run() {
try {
if (!dictFile.exists() || isNeededToRecreate()) {
// If the dictionary file does not exist or contents have been updated,
// generate a new one.
createNewDictionaryLocked();
} else if (getBinaryDictionary() == null) {
// Otherwise, load the existing dictionary.
loadBinaryDictionaryLocked();
final BinaryDictionary binaryDictionary = getBinaryDictionary();
if (binaryDictionary != null && !(isValidDictionaryLocked()
// TODO: remove the check below
&& matchesExpectedBinaryDictFormatVersionForThisType(
binaryDictionary.getFormatVersion()))) {
// Binary dictionary or its format version is not valid. Regenerate
// the dictionary file. createNewDictionaryLocked will remove the
// existing files if appropriate.
createNewDictionaryLocked();
}
}
clearNeedsToRecreate();
} finally {
isReloading.set(false);
}
}
});
}
示例15: wasClosedHandlerCalled
import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
boolean wasClosedHandlerCalled(HRegionInfo hri) {
AtomicBoolean b = closedRegionHandlerCalled.get(hri);
//compareAndSet to be sure that unit tests don't see stale values. Means,
//we will return true exactly once unless the handler code resets to true
//this value.
return b == null ? false : b.compareAndSet(true, false);
}