本文整理汇总了Java中java.util.concurrent.atomic.AtomicInteger.getAndIncrement方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicInteger.getAndIncrement方法的具体用法?Java AtomicInteger.getAndIncrement怎么用?Java AtomicInteger.getAndIncrement使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.atomic.AtomicInteger
的用法示例。
在下文中一共展示了AtomicInteger.getAndIncrement方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testGetItemsIsCalledIncreasing
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testGetItemsIsCalledIncreasing() {
final AtomicBoolean called = new AtomicBoolean(false);
final AtomicInteger calledCount = new AtomicInteger();
ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
@Override
public List<Object> getPreloadItems(int position) {
called.set(true);
final int count = calledCount.getAndIncrement();
assertEquals(11 + count, position);
return super.getPreloadItems(position);
}
};
ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
preloaderAdapter, preloaderAdapter, 10);
preloader.onScroll(null, 1, 10, 30);
assertEquals(10, calledCount.get());
}
示例2: testGetItemsIsNeverCalledWithEndGreaterThanTotalItems
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testGetItemsIsNeverCalledWithEndGreaterThanTotalItems() {
final AtomicBoolean called = new AtomicBoolean(false);
final AtomicInteger calledCount = new AtomicInteger();
ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
@Override
public List<Object> getPreloadItems(int position) {
called.set(true);
final int count = calledCount.getAndIncrement();
assertEquals(26 + count, position);
return super.getPreloadItems(position);
}
};
ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
preloaderAdapter, preloaderAdapter, 10);
preloader.onScroll(null, 16, 10, 30);
assertTrue(called.get());
}
示例3: testGetItemsIsCalledDecreasing
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testGetItemsIsCalledDecreasing() {
final AtomicBoolean called = new AtomicBoolean(false);
final AtomicInteger calledCount = new AtomicInteger();
ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
@NonNull
@Override
public List<Object> getPreloadItems(int position) {
// Ignore the preload caused from us starting at the end
if (position >= 40) {
return Collections.emptyList();
}
final int count = calledCount.getAndIncrement();
called.set(true);
assertEquals(28 - count, position);
return super.getPreloadItems(position);
}
};
ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
preloaderAdapter, preloaderAdapter, 10);
preloader.onScroll(null, 30, 10, 40);
preloader.onScroll(null, 29, 10, 40);
assertTrue(called.get());
}
示例4: testGetItemsIsNeverCalledWithEndGreaterThanTotalItems
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testGetItemsIsNeverCalledWithEndGreaterThanTotalItems() {
final AtomicBoolean called = new AtomicBoolean(false);
final AtomicInteger calledCount = new AtomicInteger();
ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
@NonNull
@Override
public List<Object> getPreloadItems(int position) {
called.set(true);
final int count = calledCount.getAndIncrement();
assertEquals(26 + count, position);
return super.getPreloadItems(position);
}
};
ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
preloaderAdapter, preloaderAdapter, 10);
preloader.onScroll(null, 16, 10, 30);
assertTrue(called.get());
}
示例5: normal
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void normal() {
final AtomicInteger count = new AtomicInteger();
Cancellable c = new Cancellable() {
@Override
public void cancel() throws Exception {
count.getAndIncrement();
}
};
CancellableDisposable cd = new CancellableDisposable(c);
assertFalse(cd.isDisposed());
cd.dispose();
cd.dispose();
assertTrue(cd.isDisposed());
assertEquals(1, count.get());
}
示例6: testDontPreloadItemsRepeatedlyWhileDecreasing
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testDontPreloadItemsRepeatedlyWhileDecreasing() {
final AtomicInteger called = new AtomicInteger();
ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
@NonNull
@Override
public List<Object> getPreloadItems(int position) {
if (position >= 20) {
return Collections.emptyList();
}
final int current = called.getAndIncrement();
assertEquals(19 - current, position);
return super.getPreloadItems(position);
}
};
ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
preloaderAdapter, preloaderAdapter, 10);
preloader.onScroll(null, 21, 10, 30);
preloader.onScroll(null, 20, 10, 30);
preloader.onScroll(null, 17, 10, 30);
assertEquals(13, called.get());
}
示例7: filter
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Override
protected FilterResult filter(AbstractTraceElement<? extends CatalogType> element) {
FilterResult result = FilterResult.ALLOW;
if (element instanceof TransactionTrace) {
final boolean trace = LOG.isTraceEnabled();
final String proc_name = element.getCatalogItemName();
final AtomicInteger proc_counter = this.proc_counters.get(proc_name);
if (proc_counter == null) {
if (trace) LOG.trace("Procedure " + proc_name + " is not included in whitelist. Skipping...");
result = FilterResult.SKIP;
} else {
int proc_idx = proc_counter.getAndIncrement();
int proc_rate = this.proc_rates.get(proc_name);
result = (proc_rate != 0 && proc_idx % proc_rate == 0 ? FilterResult.ALLOW : FilterResult.SKIP);
}
}
return (result);
}
示例8: withPool
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private static void withPool() throws Exception {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
// poolConfig.setMinIdle(0);
// poolConfig.setMaxIdle(5);
// poolConfig.setMaxTotal(5);
final JedisPool pool = new JedisPool(poolConfig, "127.0.0.1", 6379, 2000, "weimob123", 0);
List<Thread> tds = new ArrayList<Thread>();
final AtomicInteger ind = new AtomicInteger();
for (int i = 0; i < 50; i++) {
Thread hj = new Thread(new Runnable() {
public void run() {
for (; ind.getAndIncrement() < TOTAL_OPERATIONS; ) {
try {
Jedis j = pool.getResource();
// final String key = "foo" + i;
// j.setRedisData(key, key);
// j.getRedisData(key);
j.get("foo1");
j.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tds.add(hj);
hj.start();
}
for (Thread t : tds)
t.join();
pool.destroy();
}
示例9: shouldRetryWhenTimeoutExceptionOccursOnSend
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void shouldRetryWhenTimeoutExceptionOccursOnSend() throws Exception {
final AtomicInteger attempt = new AtomicInteger(0);
final RecordCollectorImpl collector = new RecordCollectorImpl(
new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
@Override
public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
if (attempt.getAndIncrement() == 0) {
throw new TimeoutException();
}
return super.send(record, callback);
}
},
"test");
collector.send("topic1", "3", "0", null, stringSerializer, stringSerializer, streamPartitioner);
final Long offset = collector.offsets().get(new TopicPartition("topic1", 0));
assertEquals(Long.valueOf(0L), offset);
}
示例10: newBoundaryCalledAfterWindowClosed
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void newBoundaryCalledAfterWindowClosed() {
final AtomicInteger calls = new AtomicInteger();
PublishProcessor<Integer> source = PublishProcessor.create();
final PublishProcessor<Integer> boundary = PublishProcessor.create();
Callable<Flowable<Integer>> boundaryFunc = new Callable<Flowable<Integer>>() {
@Override
public Flowable<Integer> call() {
calls.getAndIncrement();
return boundary;
}
};
TestSubscriber<Flowable<Integer>> ts = new TestSubscriber<Flowable<Integer>>();
source.window(boundaryFunc).subscribe(ts);
source.onNext(1);
boundary.onNext(1);
assertTrue(boundary.hasSubscribers());
source.onNext(2);
boundary.onNext(2);
assertTrue(boundary.hasSubscribers());
source.onNext(3);
boundary.onNext(3);
assertTrue(boundary.hasSubscribers());
source.onNext(4);
source.onComplete();
ts.assertNoErrors();
ts.assertValueCount(4);
ts.assertComplete();
assertFalse(source.hasSubscribers());
assertFalse(boundary.hasSubscribers());
}
示例11: testAddTokenChangeListener
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testAddTokenChangeListener() throws IOException {
final AtomicInteger counter = new AtomicInteger(0);
MockGoogleCredentials credentials = new MockGoogleCredentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
Date expiry = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));
return new AccessToken("token-" + counter.getAndIncrement(), expiry);
}
};
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
// Disable proactive token refresh, so only explicit refresh events are in play.
JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR, false);
final List<String> tokens = new ArrayList<>();
provider.addTokenChangeListener(new AuthTokenProvider.TokenChangeListener() {
@Override
public void onTokenChange(String token) {
tokens.add(token);
}
});
for (int i = 0; i < 10; i++) {
// Each refresh event should notify the TokenChangeListener. And since we are using a
// direct executor, the notification fires on the same thread in a blocking manner.
credentials.refresh();
assertEquals(i + 1, tokens.size());
assertToken(tokens.get(i), "token-" + i, ImmutableMap.<String, Object>of());
}
}
示例12: testShutdownNow
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* shutdownNow returns a list containing tasks that were not run,
* and those tasks are drained from the queue
*/
public void testShutdownNow() throws InterruptedException {
final int poolSize = 2;
final int count = 5;
final AtomicInteger ran = new AtomicInteger(0);
final CustomExecutor p = new CustomExecutor(poolSize);
final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
Runnable waiter = new CheckedRunnable() { public void realRun() {
threadsStarted.countDown();
try {
MILLISECONDS.sleep(2 * LONG_DELAY_MS);
} catch (InterruptedException success) {}
ran.getAndIncrement();
}};
for (int i = 0; i < count; i++)
p.execute(waiter);
await(threadsStarted);
assertEquals(poolSize, p.getActiveCount());
assertEquals(0, p.getCompletedTaskCount());
final List<Runnable> queuedTasks;
try {
queuedTasks = p.shutdownNow();
} catch (SecurityException ok) {
return; // Allowed in case test doesn't have privs
}
assertTrue(p.isShutdown());
assertTrue(p.getQueue().isEmpty());
assertEquals(count - poolSize, queuedTasks.size());
assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
assertTrue(p.isTerminated());
assertEquals(poolSize, ran.get());
assertEquals(poolSize, p.getCompletedTaskCount());
}
示例13: testBarrierAction
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* The supplied barrier action is run at barrier
*/
public void testBarrierAction() throws Exception {
final AtomicInteger count = new AtomicInteger(0);
final Runnable incCount = new Runnable() { public void run() {
count.getAndIncrement(); }};
CyclicBarrier b = new CyclicBarrier(1, incCount);
assertEquals(1, b.getParties());
assertEquals(0, b.getNumberWaiting());
b.await();
b.await();
assertEquals(0, b.getNumberWaiting());
assertEquals(2, count.get());
}
示例14: offer
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* Inserts the specified element at the tail of this queue, waiting if
* necessary up to the specified wait time for space to become available.
*
* @return {@code true} if successful, or {@code false} if
* the specified waiting time elapses before space is available
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
if (e == null) throw new NullPointerException();
long nanos = unit.toNanos(timeout);
int c = -1;
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
while (count.get() == capacity) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(new Node<E>(e));
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return true;
}
示例15: testBasicRetriesToSuccess
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private static void testBasicRetriesToSuccess(int expectedRetries, boolean wrapWithApplicationException)
throws Exception
{
RetryPolicy retryPolicy = new RetryPolicy(
new DriftClientConfig()
.setMaxRetries(expectedRetries + 10)
.setMinBackoffDelay(new Duration(1, SECONDS))
.setMaxBackoffDelay(new Duration(1, DAYS))
.setBackoffScaleFactor(2.0),
new TestingExceptionClassifier());
TestingMethodInvocationStat stat = new TestingMethodInvocationStat();
AtomicInteger attempts = new AtomicInteger();
MockMethodInvoker invoker = new MockMethodInvoker(() -> {
int currentAttempts = attempts.getAndIncrement();
if (currentAttempts < expectedRetries) {
return immediateFailedFuture(createClassifiedException(true, NORMAL, wrapWithApplicationException));
}
return immediateFuture(SUCCESS);
});
DriftMethodInvocation<?> methodInvocation = createDriftMethodInvocation(retryPolicy, stat, invoker, new TestingAddressSelector(100), systemTicker());
assertEquals(methodInvocation.get(), SUCCESS);
assertEquals(attempts.get(), expectedRetries + 1);
stat.assertSuccess(expectedRetries);
assertDelays(invoker, retryPolicy, expectedRetries);
}