本文整理匯總了Java中java.util.concurrent.atomic.AtomicInteger.incrementAndGet方法的典型用法代碼示例。如果您正苦於以下問題:Java AtomicInteger.incrementAndGet方法的具體用法?Java AtomicInteger.incrementAndGet怎麽用?Java AtomicInteger.incrementAndGet使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.atomic.AtomicInteger
的用法示例。
在下文中一共展示了AtomicInteger.incrementAndGet方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: test
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
void test(String[] args) throws Throwable {
for (int how=0; how<4; how++) {
final CountDownLatch done = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger(0);
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
checkScheduledExecutionTime(this);
count.incrementAndGet();
done.countDown();
}};
scheduleNow(timer, task, how);
done.await();
equal(count.get(), 1);
checkScheduledExecutionTime(task);
if (new java.util.Random().nextBoolean())
sleep(10);
check(task.cancel());
timer.cancel();
checkScheduledExecutionTime(task);
}
}
示例2: fromActionTwice
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void fromActionTwice() {
final AtomicInteger atomicInteger = new AtomicInteger();
Action run = new Action() {
@Override
public void run() throws Exception {
atomicInteger.incrementAndGet();
}
};
Maybe.fromAction(run)
.test()
.assertResult();
assertEquals(1, atomicInteger.get());
Maybe.fromAction(run)
.test()
.assertResult();
assertEquals(2, atomicInteger.get());
}
示例3: requestAfterExecuteThrowingAlsoThrows
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test public void requestAfterExecuteThrowingAlsoThrows() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a = new Object() {
@Override public String toString() {
writeCount.incrementAndGet();
throw new RuntimeException("Broken!");
}
};
try {
service.postRequestBody(a);
fail();
} catch (RuntimeException e) {
assertThat(e).hasMessage("Broken!");
}
assertThat(writeCount.get()).isEqualTo(1);
}
示例4: requestBeforeExecuteCreates
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test public void requestBeforeExecuteCreates() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
Service service = retrofit.create(Service.class);
server.enqueue(new MockResponse());
final AtomicInteger writeCount = new AtomicInteger();
Object a = new Object() {
@Override public String toString() {
writeCount.incrementAndGet();
return "Hello";
}
};
Call<String> call = service.postRequestBody(a);
call.request();
assertThat(writeCount.get()).isEqualTo(1);
call.execute();
assertThat(writeCount.get()).isEqualTo(1);
}
示例5: readTag
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
* Reads a DER tag from the stream.
*
* @param bytesRead Will be updated with the number of bytes read from the stream.
* @param expectedFlags A set of DER tags that are expected.
* @return A DER tag read from the stream.
*/
public int readTag(AtomicInteger bytesRead, DerTag... expectedFlags)
throws DerEncodingException, IOException {
int tag = in.read();
bytesRead.incrementAndGet();
if (tag < 0) {
throw new DerEncodingException("Expected tag, got end of stream.");
}
for (DerTag expected : expectedFlags) {
tag -= expected.getTag();
}
if (tag < 0) {
throw new DerEncodingException("Some flags are missing resulting in a tag value of < 0.");
}
return tag;
}
示例6: testRepeatedExecution
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void testRepeatedExecution() throws InterruptedException {
ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
Executors.defaultThreadFactory());
final AtomicInteger counter = new AtomicInteger();
Runnable run = new Runnable() {
public void run() {
counter.incrementAndGet();
}
};
ScheduledFuture f = ex.scheduleAtFixedRate(run, 0, 1, TimeUnit.SECONDS);
Awaitility.await().atMost(30, TimeUnit.SECONDS)
.until(() -> assertEquals("Task was not executed repeatedly", true, counter.get() > 1));
Awaitility.await().atMost(30, TimeUnit.SECONDS)
.until(() -> assertEquals("The task could not be cancelled", true, f.cancel(true)));
Awaitility.await().atMost(30, TimeUnit.SECONDS)
.until(() -> assertEquals("Task was not cancelled within 30 sec", true, f.isCancelled()));
int oldValue = counter.get();
Thread.sleep(5000);
assertEquals("Task was not cancelled", oldValue, counter.get());
}
示例7: oneStartOnly
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void oneStartOnly() {
final AtomicInteger startCount = new AtomicInteger();
TestSubscriber<Integer> ts = new TestSubscriber<Integer>() {
@Override
public void onStart() {
startCount.incrementAndGet();
}
};
PublishProcessor<Integer> ps = PublishProcessor.create();
ps.publish(new Function<Flowable<Integer>, Flowable<Integer>>() {
@Override
public Flowable<Integer> apply(Flowable<Integer> o) {
return o.take(1);
}
}).subscribe(ts);
Assert.assertEquals(1, startCount.get());
}
示例8: ArrayElement
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
ArrayElement(
final PsiElement arrayElement,
final AtomicInteger elementIndex
) {
if (arrayElement instanceof ArrayHashElement) {
key = ((ArrayHashElement) arrayElement).getKey();
value = ((ArrayHashElement) arrayElement).getValue();
}
else {
key = PhpPsiElementFactory.createFromText(arrayElement.getProject(), LeafPsiElement.class, String.valueOf(elementIndex.get()));
value = ((PhpPsiElement) arrayElement).getFirstPsiChild();
isIndexed = true;
elementIndex.incrementAndGet();
}
}
示例9: process
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
*
* @param id The id to check for ratelimits
* @return false if the id is ratelimited
*/
public boolean process(String id) {
AtomicInteger currentLimit = idsRateLimited.computeIfAbsent(id, k -> new AtomicInteger());
if (currentLimit.get() >= max) return false;
currentLimit.incrementAndGet();
TASK_PROCESSOR.addTask(System.currentTimeMillis() + timeout, currentLimit::decrementAndGet);
return true;
}
示例10: pgNotify
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
void pgNotify() throws InterruptedException {
DatabaseWrapper wrapper = new DatabaseWrapper(requireConnection());
int interval = 100;
String channel = "foo";
String payload = "bar";
AtomicInteger exceptions = new AtomicInteger(0);
NotificationService ns = new NotificationService(getTestJdbcUrl(), NotifyTest.class.getSimpleName(),
interval, e -> exceptions.incrementAndGet());
AtomicInteger notifications = new AtomicInteger(0);
AtomicBoolean isBar = new AtomicBoolean(false);
ns.addListener(notification -> {
notifications.getAndIncrement();
isBar.set(notification.getParameter().equals(payload));
}, channel);
Thread.sleep(interval * 2);
wrapper.notif(channel, payload);
Thread.sleep(interval * 2);
Assertions.assertEquals(0, exceptions.get(), "NotificationService threw exceptions");
Assertions.assertEquals(1, notifications.get(), "Did not receive notification");
Assertions.assertTrue(isBar.get(), "Payload was wrong");
ns.shutdown();
}
示例11: multipleHandlers
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void multipleHandlers()
{
final SpyImpl support = new SpyImpl( new ArezContext() );
final Object event = new Object();
final AtomicInteger callCount1 = new AtomicInteger();
final AtomicInteger callCount2 = new AtomicInteger();
final AtomicInteger callCount3 = new AtomicInteger();
final SpyEventHandler handler1 = e -> callCount1.incrementAndGet();
final SpyEventHandler handler2 = e -> callCount2.incrementAndGet();
final SpyEventHandler handler3 = e -> callCount3.incrementAndGet();
support.addSpyEventHandler( handler1 );
support.addSpyEventHandler( handler2 );
support.addSpyEventHandler( handler3 );
assertEquals( support.getSpyEventHandlers().size(), 3 );
support.reportSpyEvent( event );
assertEquals( callCount1.get(), 1 );
assertEquals( callCount2.get(), 1 );
assertEquals( callCount3.get(), 1 );
support.reportSpyEvent( event );
assertEquals( callCount1.get(), 2 );
assertEquals( callCount2.get(), 2 );
assertEquals( callCount3.get(), 2 );
}
示例12: dispose_releasesResources
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void dispose_releasesResources()
throws Throwable
{
final ArezContext context = Arez.context();
final Observable observable = context.createObservable();
final AtomicBoolean result = new AtomicBoolean();
final AtomicInteger conditionRun = new AtomicInteger();
final AtomicInteger effectRun = new AtomicInteger();
final String name = ValueUtil.randomString();
final boolean mutation = true;
final SafeFunction<Boolean> condition = () -> {
conditionRun.incrementAndGet();
observable.reportObserved();
return result.get();
};
final SafeProcedure procedure = effectRun::incrementAndGet;
final Watcher watcher = new Arez_Watcher( name, mutation, condition, procedure );
assertEquals( conditionRun.get(), 1 );
assertEquals( effectRun.get(), 0 );
assertEquals( Disposable.isDisposed( watcher ), false );
result.set( true );
Disposable.dispose( watcher );
assertEquals( Disposable.isDisposed( watcher ), true );
context.action( ValueUtil.randomString(), true, observable::reportChanged );
assertEquals( conditionRun.get(), 1 );
assertEquals( effectRun.get(), 0 );
}
示例13: testReschedule
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
* Test to make sure we reschedule the task for execution if it has already in progress.
*/
@Test
public void testReschedule() throws Exception {
ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
OneTaskOnlyExecutor decorator = new OneTaskOnlyExecutor(ex);
final CountDownLatch taskRunning = new CountDownLatch(1);
final CountDownLatch continueTask = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
Callable waitForLatch = new Callable() {
public Object call() throws Exception {
taskRunning.countDown();
continueTask.await();
counter.incrementAndGet();
return null;
}
};
Runnable increment = new Runnable() {
public void run() {
counter.incrementAndGet();
}
};
decorator.schedule(waitForLatch, 0, TimeUnit.SECONDS);
taskRunning.await();
decorator.schedule(increment, 0, TimeUnit.SECONDS);
assertEquals(0, counter.get());
continueTask.countDown();
ex.shutdown();
ex.awaitTermination(60, TimeUnit.SECONDS);
assertEquals(2, counter.get());
}
示例14: checkNodes
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
public static void checkNodes(Ethereum ethereum, CommonConfig commonConfig, AtomicInteger fatalErrors) {
try {
Source<byte[], byte[]> stateDS = commonConfig.stateSource();
byte[] stateRoot = ethereum.getBlockchain().getBestBlock().getHeader().getStateRoot();
Integer rootsSize = getReferencedTrieNodes(stateDS, true, stateRoot);
testLogger.info("Node validation successful");
testLogger.info("Non-unique node size: {}", rootsSize);
} catch (Exception | AssertionError ex) {
testLogger.error("Node validation error", ex);
fatalErrors.incrementAndGet();
}
}
示例15: run
import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
void run() throws Exception {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final ObjectName observedName = new ObjectName("a:b=c");
final ObjectName monitorName = new ObjectName("a:type=Monitor");
mbs.registerMBean(new StringMonitor(), monitorName);
final StringMonitorMBean monitorProxy =
JMX.newMBeanProxy(mbs, monitorName, StringMonitorMBean.class);
final TestMBean observedProxy =
JMX.newMBeanProxy(mbs, observedName, TestMBean.class);
final Runnable sensitiveThing = new Runnable() {
public void run() {
doSensitiveThing(monitorProxy, observedName);
}
};
final Runnable nothing = new Runnable() {
public void run() {}
};
final Runnable withinGetAttribute =
(when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;
mbs.registerMBean(new Test(withinGetAttribute), observedName);
monitorProxy.addObservedObject(observedName);
monitorProxy.setObservedAttribute("Thing");
monitorProxy.setStringToCompare("old");
monitorProxy.setGranularityPeriod(10L); // 10 ms
monitorProxy.setNotifyDiffer(true);
final int initGetCount = observedProxy.getGetCount();
monitorProxy.start();
int getCount = initGetCount;
for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
getCount = observedProxy.getGetCount();
if (getCount != initGetCount)
break;
Thread.sleep(10);
}
if (getCount <= initGetCount)
throw new Exception("Test failed: presumable deadlock");
// This won't show up as a deadlock in CTRL-\ or in
// ThreadMXBean.findDeadlockedThreads(), because they don't
// see that thread A is waiting for thread B (B.join()), and
// thread B is waiting for a lock held by thread A
// Now we know the monitor has observed the initial value,
// so if we want to test notify behaviour we can trigger by
// exceeding the threshold.
if (when == When.IN_NOTIFY) {
final AtomicInteger notifCount = new AtomicInteger();
final NotificationListener listener = new NotificationListener() {
public void handleNotification(Notification n, Object h) {
Thread t = new Thread(sensitiveThing);
t.start();
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
notifCount.incrementAndGet();
}
};
mbs.addNotificationListener(monitorName, listener, null, null);
observedProxy.setThing("new");
for (int i = 0; i < 500 && notifCount.get() == 0; i++)
Thread.sleep(10);
if (notifCount.get() == 0)
throw new Exception("Test failed: presumable deadlock");
}
}