下面列出了java.util.concurrent.atomic.AtomicInteger#getAndSet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testFileScan() throws Exception {
File file = new File("build");
FileScanner fileScanner = new FileScanner(file,10);
AtomicInteger counter = new AtomicInteger();
counter.getAndSet(0);
Listener listener = event -> counter.getAndIncrement();
fileScanner.registerListener(listener);
Thread f = new Thread(fileScanner);
f.start();
TimeUnit.MILLISECONDS.sleep(50);
FileWriter myWriter = new FileWriter("build/test.txt");
myWriter.write("test");
myWriter.close();
TimeUnit.MILLISECONDS.sleep(50);
FileUtils.deleteDir(new File("build/test.txt"));
TimeUnit.MILLISECONDS.sleep(50);
assertEquals(2,counter.get());
}
public static void main(String[] args) {
int temValue = 0;
AtomicInteger value = new AtomicInteger(0);
temValue = value.getAndSet(3);
// 首先get,获取到当前value的值为0,并赋值给temValue,之后设置新值3,此时value为3
System.out.println("temValue = " + temValue + " value = " + value);
temValue = value.getAndIncrement();
System.out.println("temValue = " + temValue + " value = " + value);
temValue = value.getAndDecrement();
System.out.println("temValue = " + temValue + " value = " + value);
temValue = value.getAndAdd(10);
System.out.println("temValue = " + temValue + " value = " + value);
}
public static <T> T invoke(Callable<T> method, DomainNames domain) throws Exception {
if (!initialized) {
throw new IllegalStateException("RetryPolicyAdapter should be initialized before invoking api calls");
}
AtomicInteger retryCountForDomain = getRetryCountForDomain(domain);
while (retryCountForDomain.get() < DEFAULT_MAX_RETRIES) {
try {
sleepIfLimitIsExceeded(domain);
T result = method.call();
retryCountForDomain.getAndSet(0);
return result;
} catch (ApiException e) {
if (isRateLimited(e) || isInternalServerError(e)) {
sleepAndIncrementCounter(domain);
logger.info("Retrying, # of retries: " + retryCountForDomain + " error code:" + e.getCode());
} else {
throw e;
}
}
}
throw new Exception("Max number of api call tries exceeded");
}
private static AtomicInteger createTextureHandle() {
int newHandle = -1;
if (HANDLE_CACHE.size() >= MAX_TEXTURES) {
AtomicInteger reusedHandle = HANDLE_CACHE.poll();
newHandle = reusedHandle.getAndSet(-1);
}
if (newHandle == -1) {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
newHandle = textures[0];
}
AtomicInteger result = new AtomicInteger(newHandle);
HANDLE_CACHE.add(result);
return result;
}
@Test
public void forwardsCalls() {
AutoConfiguredLoadBalancer lb =
(AutoConfiguredLoadBalancer) lbf.newLoadBalancer(new TestHelper());
final AtomicInteger calls = new AtomicInteger();
TestLoadBalancer testlb = new TestLoadBalancer() {
@Override
public void handleNameResolutionError(Status error) {
calls.getAndSet(1);
}
@Override
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
calls.getAndSet(2);
}
@Override
public void shutdown() {
calls.getAndSet(3);
}
};
lb.setDelegate(testlb);
lb.handleNameResolutionError(Status.RESOURCE_EXHAUSTED);
assertThat(calls.getAndSet(0)).isEqualTo(1);
lb.handleSubchannelState(null, null);
assertThat(calls.getAndSet(0)).isEqualTo(2);
lb.shutdown();
assertThat(calls.getAndSet(0)).isEqualTo(3);
}
/**
* Updates the number of threads that can be simultaneously used for
* executing processors.
*
* @param maxThreadCount This method must be called while holding the write
* lock!
*/
private void setMaxThreadCount(final int maxThreadCount, final FlowEngine engine, final AtomicInteger maxThreads) {
if (maxThreadCount < 1) {
throw new IllegalArgumentException();
}
maxThreads.getAndSet(maxThreadCount);
if (null != engine && engine.getCorePoolSize() < maxThreadCount) {
engine.setCorePoolSize(maxThreads.intValue());
}
}
@Test
public void testClear() {
AsyncLoadingCache<String, Integer> cachedResult = new AsyncLoadingCache<>(30000);
AtomicInteger value = new AtomicInteger(111);
Supplier<CompletableFuture<Integer>> supplier = () -> CompletableFuture.supplyAsync(value::get);
consistently("we get the original value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(111), 10, 2);
value.getAndSet(222);
consistently("we still see the cached value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(111), 10, 2);
cachedResult.clear();
consistently("we see the new value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(222), 10, 2);
}
public static void main(final String[] args) throws Exception
{
// * base-7.0.2.2
// pipeline= 2 (ack every 1): OK, > 60000 updates/sec
// pipeline= 4 (ack every 2): OK, >100000 updates/sec
// pipeline=10 (ack every 5): Stops after 4 updates
int pipeline = 4;
if (args.length == 1)
pipeline = Integer.parseInt(args[0]);
final PVAClient pva = new PVAClient();
final PVAChannel channel = pva.getChannel("spam");
channel.connect().get(5, TimeUnit.SECONDS);
AtomicInteger updates = new AtomicInteger();
final AutoCloseable subscription = channel.subscribe("", pipeline, (ch, changes, overruns, data) ->
{
updates.incrementAndGet();
// System.out.println(data);
});
while (true)
{
TimeUnit.SECONDS.sleep(10);
final int got = updates.getAndSet(0);
System.err.println("pipeline=" + pipeline + " got " + got + " updates in 10 seconds, " + got/10 + " per sec");
}
// subscription.close();
// channel.close();
// pva.close();
}
private static void sleepIfLimitIsExceeded(DomainNames domain) throws InterruptedException {
AtomicInteger apiCallCount = getCounterForDomain(domain);
if ((apiCallCount.get()) >= (getLimitForDomain(domain))) {
long current = System.currentTimeMillis();
int sleepTime = 60000 - (int) (current - startTime);
startTime = current;
apiCallCount.getAndSet(0);
logger.warn("thread will sleep for :" + sleepTime + " milliseconds.");
Thread.sleep(sleepTime);
}
}
@SuppressWarnings("deprecation")
@Test
public void forwardsCalls() {
AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());
final AtomicInteger calls = new AtomicInteger();
TestLoadBalancer testlb = new TestLoadBalancer() {
@Override
public void handleNameResolutionError(Status error) {
calls.getAndSet(1);
}
@Override
public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
calls.getAndSet(2);
}
@Override
public void shutdown() {
calls.getAndSet(3);
}
};
lb.setDelegate(testlb);
lb.handleNameResolutionError(Status.RESOURCE_EXHAUSTED);
assertThat(calls.getAndSet(0)).isEqualTo(1);
lb.handleSubchannelState(null, null);
assertThat(calls.getAndSet(0)).isEqualTo(2);
lb.shutdown();
assertThat(calls.getAndSet(0)).isEqualTo(3);
}
/**
* Updates the number of threads that can be simultaneously used for executing processors.
* This method must be called while holding the write lock!
*
* @param maxThreadCount max number of threads
*/
private void setMaxThreadCount(final int maxThreadCount, final FlowEngine engine, final AtomicInteger maxThreads) {
if (maxThreadCount < 1) {
throw new IllegalArgumentException("Cannot set max number of threads to less than 2");
}
maxThreads.getAndSet(maxThreadCount);
if (null != engine && engine.getCorePoolSize() < maxThreadCount) {
engine.setCorePoolSize(maxThreads.intValue());
}
}
@OpenCLMapping(atomic32 = true, mapTo = "atomic_xchg")
protected final int atomicXchg(AtomicInteger p, int newVal) {
return p.getAndSet(newVal);
}