本文整理汇总了Java中java.util.concurrent.atomic.AtomicInteger类的典型用法代码示例。如果您正苦于以下问题:Java AtomicInteger类的具体用法?Java AtomicInteger怎么用?Java AtomicInteger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AtomicInteger类属于java.util.concurrent.atomic包,在下文中一共展示了AtomicInteger类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: WeightedRoundRobinMultiplexer
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
public WeightedRoundRobinMultiplexer(int aNumQueues, String ns,
Configuration conf) {
if (aNumQueues <= 0) {
throw new IllegalArgumentException("Requested queues (" + aNumQueues +
") must be greater than zero.");
}
this.numQueues = aNumQueues;
this.queueWeights = conf.getInts(ns + "." +
IPC_CALLQUEUE_WRRMUX_WEIGHTS_KEY);
if (this.queueWeights.length == 0) {
this.queueWeights = getDefaultQueueWeights(this.numQueues);
} else if (this.queueWeights.length != this.numQueues) {
throw new IllegalArgumentException(ns + "." +
IPC_CALLQUEUE_WRRMUX_WEIGHTS_KEY + " must specify exactly " +
this.numQueues + " weights: one for each priority level.");
}
this.currentQueueIndex = new AtomicInteger(0);
this.requestsLeft = new AtomicInteger(this.queueWeights[0]);
LOG.info("WeightedRoundRobinMultiplexer is being used.");
}
示例2: testNodes9
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void testNodes9() throws IOException, InterruptedException,
KeeperException {
int testIterations = 9;
final CountDownLatch latch = new CountDownLatch(testIterations);
final AtomicInteger failureCounter = new AtomicInteger();
for (int i = 0; i < testIterations; i++) {
runElectionSupportThread(latch, failureCounter);
}
Assert.assertEquals(0, failureCounter.get());
if (!latch.await(10, TimeUnit.SECONDS)) {
logger
.info(
"Waited for all threads to start, but timed out. We had {} failures.",
failureCounter);
}
}
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:22,代码来源:LeaderElectionSupportTest.java
示例3: 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() {
@NonNull
@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());
}
示例4: test211193
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
public void test211193() throws Exception {
writeFilesAndWaitForScan(src,
new File("t/A.java", "package t;\n"
+ "public class A {\n"
+ " public static void foo() {\n"
+ " int someArray[] = {};\n"
+ " }\n"
+ "}"));
FileObject testFile = src.getFileObject("t/A.java");
DataObject testFileDO = DataObject.find(testFile);
EditorCookie ec = testFileDO.getLookup().lookup(EditorCookie.class);
ec.open();
ec.getOpenedPanes()[0].setCaretPosition(71);
ec.getOpenedPanes()[0].moveCaretPosition(80);
final AtomicInteger called = new AtomicInteger();
ContextAnalyzer.SHOW = new ContextAnalyzer.ShowUI() {
@Override
public void show(RefactoringUI ui, TopComponent activetc) {
assertNotNull(ui);
called.incrementAndGet();
}
};
int expectedCount = 0;
new RefactoringActionsProvider().doRename(Lookups.fixed(ec));
assertEquals(++expectedCount, called.get());
}
示例5: expectPolls
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
private CountDownLatch expectPolls(int minimum, final AtomicInteger count) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(minimum);
// Note that we stub these to allow any number of calls because the thread will continue to
// run. The count passed in + latch returned just makes sure we get *at least* that number of
// calls
EasyMock.expect(sourceTask.poll())
.andStubAnswer(new IAnswer<List<SourceRecord>>() {
@Override
public List<SourceRecord> answer() throws Throwable {
count.incrementAndGet();
latch.countDown();
return RECORDS;
}
});
// Fallout of the poll() call
expectSendRecordAnyTimes();
return latch;
}
示例6: test
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void test() throws InterruptedException {
AtomicInteger incrementor = new AtomicInteger();
ResettableEvent are = new ResettableEvent(true);
ResettableEvent done = new ResettableEvent(false);
ExecutorService threadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
threadPool.submit(Interrupted.unchecked(() -> {
are.getAndReset();
incrementor.incrementAndGet();
done.set();
}));
}
done.getAndReset();
Thread.sleep(100); // give a little time to other threads to increment, if there's indeed a bug
assertEquals(1, incrementor.get());
threadPool.shutdownNow();
}
示例7: offer
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
/**
* Inserts the specified element at the tail of this queue if it is possible to do so immediately
* without exceeding the queue's capacity, returning {@code true} upon success and {@code false}
* if this queue is full. When using a capacity-restricted queue, this method is generally
* preferable to method {@link BlockingQueue#add add}, which can fail to insert an element only by
* throwing an exception.
*
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
final AtomicInteger count = this.count;
if (count.get() >= capacity) // GEMFIRE changed == to >=
return false;
int c = -1;
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
if (count.get() < capacity) {
enqueue(e);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
}
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return c >= 0;
}
示例8: testFutures
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void testFutures() {
final Callable<Integer> callable1 = successCallable(999, 100);
final Callable<String> callable2 = successCallable("HI", 1000);
ExecutorService es = deferredManager.getExecutorService();
Future<Integer> future1 = es.submit(callable1);
Future<String> future2 = es.submit(callable2);
final AtomicInteger doneCount = new AtomicInteger();
deferredManager.when(future1, future2).done(new DoneCallback<MultipleResults>() {
@Override
public void onDone(MultipleResults result) {
Assert.assertEquals(2, result.size());
Assert.assertEquals(999, result.get(0).getResult());
Assert.assertEquals("HI", result.get(1).getResult());
doneCount.incrementAndGet();
}
});
waitForCompletion();
Assert.assertEquals(1, doneCount.get());
}
示例9: testProvider_StaticNumberProvider
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void testProvider_StaticNumberProvider() {
PluggableDefaultValueStrategy strategy = new PluggableDefaultValueStrategy();
strategy.addProvider(new StaticNumberProvider(42L));
assertEquals(Long.valueOf(42L), strategy.getDefaultValue(TestUtils.getCM("", "", "", Long.class, false), Long.class));
assertNull(strategy.getDefaultValue(TestUtils.getCM("", "", "", String.class, false), String.class));
assertEquals(42L, (long) strategy.getDefaultValue(TestUtils.getCM("", "", "", Long.class, true), Long.class));
assertEquals(42, (int) strategy.getDefaultValue(TestUtils.getCM("", "", "", Integer.class, true), Integer.class));
assertEquals(42.0, strategy.getDefaultValue(TestUtils.getCM("", "", "", Double.class, true), Double.class), 0.0);
assertEquals(42.0f, strategy.getDefaultValue(TestUtils.getCM("", "", "", Float.class, true), Float.class), 0f);
assertEquals(new BigDecimal(42), strategy.getDefaultValue(TestUtils.getCM("", "", "", BigDecimal.class, true), BigDecimal.class));
assertEquals((byte) 42, (byte) strategy.getDefaultValue(TestUtils.getCM("", "", "", Byte.class, true), Byte.class));
assertEquals((short) 42, (short) strategy.getDefaultValue(TestUtils.getCM("", "", "", Short.class, true), Short.class));
assertEquals(42, strategy.getDefaultValue(TestUtils.getCM("", "", "", AtomicInteger.class, true), AtomicInteger.class).get());
assertEquals(42L, strategy.getDefaultValue(TestUtils.getCM("", "", "", AtomicLong.class, true), AtomicLong.class).get());
assertNull(new StaticNumberProvider(BigDecimal.ONE).convertNumber(new BigDecimal(0), String.class));
}
示例10: createDefaultThreadPool
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
public static ThreadPoolExecutor createDefaultThreadPool() {
// 控制最多4个keep在pool中
int corePoolSize = Math.min(4, CPU_CORE);
return new ThreadPoolExecutor(
corePoolSize,
Integer.MAX_VALUE,
DEFAULT_CACHE_SENCOND, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadFactory() {
static final String NAME = "lite-";
AtomicInteger IDS = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, NAME + IDS.getAndIncrement());
}
},
new ThreadPoolExecutor.DiscardPolicy());
}
示例11: testSerializationWithMapMaker_preservesIdentityKeyEquivalence
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
public void testSerializationWithMapMaker_preservesIdentityKeyEquivalence() {
ConcurrentMap<String, AtomicInteger> map =
new MapMaker().keyEquivalence(Equivalence.identity()).makeMap();
ConcurrentHashMultiset<String> multiset = ConcurrentHashMultiset.create(map);
multiset = reserializeAndAssert(multiset);
String s1 = new String("a");
String s2 = new String("a");
assertEquals(s1, s2); // Stating the obvious.
assertTrue(s1 != s2); // Stating the obvious.
multiset.add(s1);
assertTrue(multiset.contains(s1));
assertFalse(multiset.contains(s2));
assertEquals(1, multiset.count(s1));
assertEquals(0, multiset.count(s2));
}
示例12: testPartialSuccess
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void testPartialSuccess() throws Exception {
repeat(2, i -> {
int attempts = i + 1;
failures.set(attempts);
AtomicInteger failoverCalls = new AtomicInteger();
AggregateResult<String> result = get(sender.get().withFailover(context -> {
failoverCalls.incrementAndGet();
return context.retry();
}).aggregate("test"));
assertTrue(result.isSuccess());
assertEquals(channels.size(), result.results().size());
assertEquals(attempts, failoverCalls.get());
});
}
示例13: 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);
}
示例14: formatToCharacterIterator
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
/**
* Formats an Object producing an <code>AttributedCharacterIterator</code>.
* You can use the returned <code>AttributedCharacterIterator</code>
* to build the resulting String, as well as to determine information
* about the resulting String.
* <p>
* Each attribute key of the AttributedCharacterIterator will be of type
* <code>NumberFormat.Field</code>, with the attribute value being the
* same as the attribute key.
*
* @exception NullPointerException if obj is null.
* @exception IllegalArgumentException when the Format cannot format the
* given object.
* @exception ArithmeticException if rounding is needed with rounding
* mode being set to RoundingMode.UNNECESSARY
* @param obj The object to format
* @return AttributedCharacterIterator describing the formatted value.
* @since 1.4
*/
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
CharacterIteratorFieldDelegate delegate =
new CharacterIteratorFieldDelegate();
StringBuffer sb = new StringBuffer();
if (obj instanceof Double || obj instanceof Float) {
format(((Number)obj).doubleValue(), sb, delegate);
} else if (obj instanceof Long || obj instanceof Integer ||
obj instanceof Short || obj instanceof Byte ||
obj instanceof AtomicInteger || obj instanceof AtomicLong) {
format(((Number)obj).longValue(), sb, delegate);
} else if (obj instanceof BigDecimal) {
format((BigDecimal)obj, sb, delegate);
} else if (obj instanceof BigInteger) {
format((BigInteger)obj, sb, delegate, false);
} else if (obj == null) {
throw new NullPointerException(
"formatToCharacterIterator must be passed non-null object");
} else {
throw new IllegalArgumentException(
"Cannot format given Object as a Number");
}
return delegate.getIterator(sb.toString());
}
示例15: test_received_request_twoway_error_reqeustBroken
import java.util.concurrent.atomic.AtomicInteger; //导入依赖的package包/类
@Test
public void test_received_request_twoway_error_reqeustBroken() throws RemotingException{
final Request request = new Request();
request.setTwoWay(true);
request.setData(new BizException());
request.setBroken(true);
final AtomicInteger count = new AtomicInteger(0);
final Channel mchannel = new MockedChannel(){
@Override
public void send(Object message) throws RemotingException {
Response res = (Response)message;
Assert.assertEquals(request.getId(), res.getId());
Assert.assertEquals(request.getVersion(), res.getVersion());
Assert.assertEquals(Response.BAD_REQUEST, res.getStatus());
Assert.assertNull(res.getResult());
Assert.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
count.incrementAndGet();
}
};
HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler());
hexhandler.received(mchannel, request);
Assert.assertEquals(1, count.get());
}