本文整理汇总了Java中java.util.concurrent.atomic.AtomicInteger.set方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicInteger.set方法的具体用法?Java AtomicInteger.set怎么用?Java AtomicInteger.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.atomic.AtomicInteger
的用法示例。
在下文中一共展示了AtomicInteger.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testOfferInStealQueueFromShouldUnblock
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testOfferInStealQueueFromShouldUnblock() throws InterruptedException {
final AtomicInteger taken = new AtomicInteger();
Thread consumer = new Thread() {
@Override
public void run() {
try {
Integer n = stealJobQueue.take();
taken.set(n);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
consumer.start();
stealFromQueue.offer(3);
consumer.join(1000);
assertEquals(3, taken.get());
consumer.interrupt(); //Ensure the consumer thread will stop.
}
示例2: respondSuccess
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void respondSuccess() throws CheckedFutureException {
Promise<Integer> p = Promise.apply();
AtomicInteger result = new AtomicInteger(-1);
AtomicBoolean failure = new AtomicBoolean(false);
Responder<Integer> r = new Responder<Integer>() {
@Override
public void onException(Throwable ex) {
failure.set(true);
}
@Override
public void onValue(Integer value) {
result.set(value);
}
};
Future<Integer> f = p.respond(r);
p.setValue(1);
assertEquals(1, result.get());
assertFalse(failure.get());
assertEquals(new Integer(1), get(p));
assertEquals(new Integer(1), get(f));
}
示例3: _checkEndingStampingTag
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* Decrement the counter if this tag returns true from {@link #isStampingTag()}. Allows the code
* to check if we are outside of all stamping component tags.
*
* @see #_checkStartingStampingTag(Map)
*/
private void _checkEndingStampingTag()
{
if (isStampingTag())
{
Map<Object, Object> facesContextAttributes = getFacesContext().getAttributes();
AtomicInteger count = (AtomicInteger)facesContextAttributes.get(_STAMPING_COUNT_KEY);
if (count.get() == 1)
{
facesContextAttributes.remove(_STAMPING_COUNT_KEY);
}
else
{
count.set(count.get() - 1);
}
}
}
示例4: testIntValue
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* intValue returns current value.
*/
public void testIntValue() {
AtomicInteger ai = new AtomicInteger();
assertEquals(0, ai.intValue());
for (int x : VALUES) {
ai.set(x);
assertEquals(x, ai.intValue());
}
}
示例5: conditionTrueForNIterations
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public static BooleanSupplier conditionTrueForNIterations(BooleanSupplier condition, int iters) {
final AtomicInteger ai = new AtomicInteger(0);
return () -> {
if (condition.getAsBoolean()) {
int i = ai.incrementAndGet();
return i >= iters;
} else {
ai.set(0);
return false;
}
};
}
示例6: argumentCapture
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/** Confirm that Retrofit encodes parameters when the call is executed, and not earlier. */
@Test public void argumentCapture() throws Exception {
AtomicInteger i = new AtomicInteger();
server.enqueue(new MockResponse().setBody("a"));
server.enqueue(new MockResponse().setBody("b"));
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new ToStringConverterFactory())
.build();
MutableParameters mutableParameters = retrofit.create(MutableParameters.class);
i.set(100);
Call<String> call1 = mutableParameters.method(i);
i.set(101);
Response<String> response1 = call1.execute();
i.set(102);
assertEquals("a", response1.body());
assertEquals("/?i=101", server.takeRequest().getPath());
i.set(200);
Call<String> call2 = call1.clone();
i.set(201);
Response<String> response2 = call2.execute();
i.set(202);
assertEquals("b", response2.body());
assertEquals("/?i=201", server.takeRequest().getPath());
}
示例7: pipeResource
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void pipeResource() throws IOException, InterruptedException {
BytesBiChannel<Pipe> pipe = IoStream.pipe();
final OutputStreamOf<Pipe> output = pipe.outputStream();
final InputStreamOf<Pipe> input = output.get().inputStream();
final AtomicInteger ai = new AtomicInteger();
Thread t = new Thread(() -> {
try {
int i;
while ((i = input.read()) != -1) {
ai.set(i);
}
} catch (IOException e) {
e.printStackTrace();
}
});
t.start();
output.write(58);
t.join(50);
output.close();
Assertions.assertThat(ai.get()).isEqualTo(58);
}
示例8: testBatchNodeRecreation
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public void testBatchNodeRecreation() throws Exception { // #211847
final List<Integer> nodesCreated = new ArrayList<Integer>();
final AtomicInteger size = new AtomicInteger(3);
class F extends ChildFactory<Integer> {
@Override protected boolean createKeys(List<Integer> keys) {
List<Integer> arr = new ArrayList<Integer>();
for (int i = 1; i <= size.get(); i++) {
arr.add(i);
}
keys.addAll(arr);
return true;
}
@Override protected Node createNodeForKey(Integer key) {
nodesCreated.add(key);
Node n = new AbstractNode(Children.LEAF);
n.setName(key.toString());
return n;
}
void refresh() {
refresh(false);
}
}
F f = new F();
Children c = Children.create(f, true);
Node root = new AbstractNode(c);
// must keep reference to nodes => each node keeps ref to ChildrenArray (its parent ChildrenArray)
// so it cannot be GCed
Node[] nodes = root.getChildren().getNodes(true);
assertEquals(3, nodes.length);
assertEquals("[1, 2, 3]", nodesCreated.toString());
LOG.info("Three elements in there!");
size.set(4);
f.refresh();
LOG.info("After refresh");
nodes = root.getChildren().getNodes(true);
assertEquals(4, nodes.length);
assertEquals("[1, 2, 3, 4]", nodesCreated.toString());
}
示例9: testGetAndIncrement
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* getAndIncrement returns previous value and increments
*/
public void testGetAndIncrement() {
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1, ai.getAndIncrement());
assertEquals(2, ai.get());
ai.set(-2);
assertEquals(-2, ai.getAndIncrement());
assertEquals(-1, ai.getAndIncrement());
assertEquals(0, ai.getAndIncrement());
assertEquals(1, ai.get());
}
示例10: refreshCacheTest
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public static void refreshCacheTest(AbstractCacheBuilder builder, long refresh, long stopRefreshAfterLastAccess) throws Exception {
AtomicInteger count = new AtomicInteger(0);
builder.loader((key) -> key + "_V" + count.getAndIncrement());
RefreshPolicy policy = RefreshPolicy.newPolicy(refresh, TimeUnit.MILLISECONDS);
builder.refreshPolicy(policy);
Cache cache = builder.buildCache();
refreshCacheTest1(cache);
cache.close();
count.set(0);
builder.getConfig().getRefreshPolicy().setStopRefreshAfterLastAccessMillis(stopRefreshAfterLastAccess);
cache = builder.buildCache();
refreshCacheTest2(cache);
cache.close();
}
示例11: testReloadAfterFailure
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public void testReloadAfterFailure() throws ExecutionException {
final AtomicInteger count = new AtomicInteger();
final Exception e = new IllegalStateException("exception to trigger failure on first load()");
CacheLoader<Integer, String> failOnceFunction = new CacheLoader<Integer, String>() {
@Override
public String load(Integer key) throws Exception {
if (count.getAndIncrement() == 0) {
throw e;
}
return key.toString();
}
};
CountingRemovalListener<Integer, String> removalListener = countingRemovalListener();
LoadingCache<Integer, String> cache = CacheBuilder.newBuilder()
.removalListener(removalListener)
.build(failOnceFunction);
try {
cache.getUnchecked(1);
fail();
} catch (UncheckedExecutionException ue) {
assertSame(e, ue.getCause());
}
assertEquals("1", cache.getUnchecked(1));
assertEquals(0, removalListener.getCount());
count.set(0);
cache.refresh(2);
checkLoggedCause(e);
assertEquals("2", cache.getUnchecked(2));
assertEquals(0, removalListener.getCount());
}
示例12: testFlagsEvents
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public void testFlagsEvents() throws Exception {
InstanceContent ic = new InstanceContent();
Lookup lookup = new AbstractLookup(ic);
final URL root1 = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(new File(getWorkDir(),"root1")));
final URL root2 = FileUtil.urlForArchiveOrDir(FileUtil.normalizeFile(new File(getWorkDir(),"root2")));
ProviderImpl defaultCP = new ProviderImpl();
final MutableCPImpl cpImpl = new MutableCPImpl(root1);
defaultCP.paths.put(ClassPath.COMPILE, ClassPathFactory.createClassPath(cpImpl));
ClassPathProviderMerger instance = new ClassPathProviderMerger(defaultCP);
ClassPathProvider result = instance.merge(lookup);
ClassPath compile = result.findClassPath(null, ClassPath.COMPILE);
assertNotNull(compile);
final AtomicInteger count = new AtomicInteger();
compile.addPropertyChangeListener((evt) -> {
if (ClassPath.PROP_FLAGS.equals(evt.getPropertyName())) {
count.incrementAndGet();
}
});
final ProviderImpl additional = new ProviderImpl();
final MutableCPImpl addCpImpl = new MutableCPImpl(root2);
addCpImpl.add(ClassPath.Flag.INCOMPLETE);
additional.paths.put(ClassPath.COMPILE, ClassPathFactory.createClassPath(addCpImpl));
ic.add(additional);
assertEquals(1, count.get());
count.set(0);
addCpImpl.remove(ClassPath.Flag.INCOMPLETE);
assertEquals(1, count.get());
count.set(0);
addCpImpl.add(ClassPath.Flag.INCOMPLETE);
assertEquals(1, count.get());
count.set(0);
}
示例13: main
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
CountDownLatch prepareLatch = new CountDownLatch(2);
AtomicInteger goLatch = new AtomicInteger(1);
Task taskA = new Task(prepareLatch, goLatch, AnnA.class);
Task taskB = new Task(prepareLatch, goLatch, AnnB.class);
taskA.start();
taskB.start();
// wait until both threads start-up
prepareLatch.await();
// let them go
goLatch.set(0);
// obtain ThreadMXBean
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
// wait for threads to finish or dead-lock
while (taskA.isAlive() || taskB.isAlive()) {
// attempt to join threads
taskA.join(500L);
taskB.join(500L);
// detect dead-lock
long[] deadlockedIds = threadBean.findMonitorDeadlockedThreads();
if (deadlockedIds != null && deadlockedIds.length > 0) {
StringBuilder sb = new StringBuilder("deadlock detected:\n\n");
for (ThreadInfo ti : threadBean.getThreadInfo(deadlockedIds, Integer.MAX_VALUE)) {
sb.append(ti);
}
throw new IllegalStateException(sb.toString());
}
}
}
示例14: sendMessage
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@POST
@Path("conversations")
@Secure
public Response sendMessage(Message message) throws InterruptedException {
final SmsManager sms = SmsManager.getDefault();
final ArrayList<String> parts = sms.divideMessage(message.getBody());
final CountDownLatch sentLatch = new CountDownLatch(parts.size());
final AtomicInteger statusCode =
new AtomicInteger(Response.Status.CREATED.getStatusCode());
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getResultCode() != Activity.RESULT_OK) {
statusCode.set(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
sentLatch.countDown();
}
};
deskDroidService.registerReceiver(receiver, new IntentFilter("com.steeplesoft.deskdroid.SMS_SENT"));
ArrayList<PendingIntent> sentPIs = new ArrayList<>();
for (int i = 0; i < parts.size(); i++) {
sentPIs.add(PendingIntent.getBroadcast(deskDroidService.getApplicationContext(), 0,
new Intent("com.steeplesoft.deskdroid.SMS_SENT"), 0));
}
sms.sendMultipartTextMessage(message.getAddress(), null, parts, sentPIs, null);
sentLatch.await(5, TimeUnit.SECONDS);
deskDroidService.unregisterReceiver(receiver);
return Response.status(statusCode.get()).build();
}
示例15: test
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void test() {
AtomicInteger ai = new AtomicInteger();
for (int i=0; i < 10000; i++) {
try {
SecureRandom random = SecureRandom.getInstance("NativePRNGNonBlocking");
ai.set(random.nextInt());
} catch (NoSuchAlgorithmException e) {
throw new UnreachableException(e);
}
}
}