本文整理汇总了Java中java.util.concurrent.atomic.AtomicInteger.get方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicInteger.get方法的具体用法?Java AtomicInteger.get怎么用?Java AtomicInteger.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.atomic.AtomicInteger
的用法示例。
在下文中一共展示了AtomicInteger.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: take
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
示例2: maxActiveCollect
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private static int maxActiveCollect(int numTasks, int parallelism, boolean privatePool) {
Set<Integer> active = new HashSet<>();
AtomicInteger maxActive = new AtomicInteger();
Set<Integer> completed = ExecUtils.collectInParallel(numTasks, parallelism, privatePool, i -> {
synchronized (active) {
active.add(i);
maxActive.set(Math.max(maxActive.get(), active.size()));
}
sleepSeconds(1);
synchronized (active) {
active.remove(i);
}
return i;
}, Collectors.toSet());
assertEquals(numTasks, completed.size());
for (int i = 0; i < numTasks; i++) {
assertTrue(completed.contains(i));
}
return maxActive.get();
}
示例3: poll
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
E x = null;
int c = -1;
long nanos = unit.toNanos(timeout);
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}
示例4: getIndex
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* Get the index of the object in the model.
*
* @param model the model
* @param object the object
* @return the index
*/
public static int getIndex(@NotNull final Spatial model, @NotNull final Object object) {
Spatial parent = model;
int parentIndex = 0;
while (parent != null) {
if (Objects.equals(parent, object)) return parentIndex;
parent = parent.getParent();
parentIndex--;
}
if (!(model instanceof Node)) {
return -1;
}
final AtomicInteger counter = new AtomicInteger(0);
final Node node = (Node) model;
final List<Spatial> children = node.getChildren();
for (final Spatial child : children) {
if (getIndex(child, object, counter)) return counter.get();
}
return -1;
}
示例5: put
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* Inserts the specified element at the tail of this queue, waiting if
* necessary for space to become available.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
示例6: 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());
}
示例7: waitWhileSessionIsActive
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* Wait while session access counter has a positive value.
*/
private void waitWhileSessionIsActive(StandardSession session)
throws InterruptedException {
long maxWaitTime = System.currentTimeMillis() + 60000;
AtomicInteger accessCount = session.accessCount;
while (accessCount.get() > 0) {
// Wait until o.a.c.connector.Request.recycle() completes,
// as it updates lastAccessedTime.
Assert.assertTrue(System.currentTimeMillis() < maxWaitTime);
Thread.sleep(200);
}
}
示例8: testAllTasksAtPriority1AreDoneFirst
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testAllTasksAtPriority1AreDoneFirst() {
final int parallelTasks = 10;
PriorityTaskQueue pq = new PriorityTaskQueue(parallelTasks, () -> null, s -> {
});
final AtomicInteger priority1Started = new AtomicInteger(parallelTasks);
final AtomicInteger errorCounter = new AtomicInteger();
Consumer<PriorityTaskQueue> prio1Task = e -> priority1Started.decrementAndGet();
Consumer<PriorityTaskQueue> prio2Task = e -> {
if (priority1Started.get() == parallelTasks) {
errorCounter.incrementAndGet();
}
};
for (int i = 0; i < parallelTasks; i++) {
pq.addTask(2, prio2Task);
pq.addTask(1, prio1Task);
}
ExecutorService executorService = Executors.newCachedThreadPool();
Queue<Exception> exceptions = new LinkedList<>();
assertThat(
pq.executeTasksAndAwaitDone(executorService, exceptions::offer, 1, TimeUnit.SECONDS),
is(true));
assertThat(exceptions.size(), is(0));
assertThat(errorCounter.get(), is(0));
executorService.shutdown();
}
示例9: size
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
/**
* {@inheritDoc}
*
* <p>If the data in the multiset is modified by any other threads during this method,
* it is undefined which (if any) of these modifications will be reflected in the result.
*/
@Override public int size() {
long sum = 0L;
for (AtomicInteger value : countMap.values()) {
sum += value.get();
}
return Ints.saturatedCast(sum);
}
示例10: assertCallbackCount
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private void assertCallbackCount(int runs, int sleep, AtomicInteger count) throws InterruptedException{
int last = count.get();
for(int i=0;i< runs ;i++){
if (last > runs) break;
Thread.sleep(sleep * 2);
System.out.println(count.get() + " " + last);
Assert.assertTrue(count.get() > last);
last = count.get();
}
//有一次同步调用callback
Assert.assertEquals(runs+1, count.get());
}
示例11: findFreeSession
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private Session findFreeSession() {
for (Entry<Session, AtomicInteger> entry : sessions.entrySet()) {
Session s = entry.getKey();
AtomicInteger availableChannels = entry.getValue();
if (s.isConnected() && availableChannels.get() > 0) {
log.log(Level.FINE, "availableChannels == {0}", new Object[]{availableChannels.get()}); // NOI18N
int remains = availableChannels.decrementAndGet();
log.log(Level.FINE, "Reuse session [{0}]. {1} channels remain...", new Object[]{System.identityHashCode(s), remains}); // NOI18N
return s;
}
}
return null;
}
示例12: testDoRetry_nofify
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Test
public void testDoRetry_nofify() throws Exception {
//初始值0
final AtomicInteger count = new AtomicInteger(0);
NotifyListener listner = new NotifyListener() {
public void notify(List<URL> urls) {
count.incrementAndGet();
//第一次抛出异常,看后面是否会再次调用到incrementAndGet
if (count.get() == 1l) {
throw new RuntimeException("test exception please ignore");
}
}
};
registry = new MockRegistry(registryUrl, new CountDownLatch(0));
registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
assertEquals(1, count.get()); //确保subscribe调用完成后刚调用过一次count.incrementAndGet
//等定时器.
for (int i = 0; i < trytimes; i++) {
System.out.println("failback notify retry ,times:" + i);
if (count.get() == 2)
break;
Thread.sleep(sleeptime);
}
assertEquals(2, count.get());
}
示例13: roundRobinSelect
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
public static HostInfo roundRobinSelect(String serviceName)
{
ArrayList<HostInfo> hostInfos=LOCALSERVER_HOSTINFOS.get(serviceName);
if(hostInfos!=null&&hostInfos.size()>0)
{
AtomicInteger atomicIndex=ROUNDROBIN_INDEX.get(serviceName);
if(atomicIndex.get()==hostInfos.size())
{
atomicIndex.set(0);
}
int index=atomicIndex.getAndAdd(1);
return hostInfos.get(index);
}
return null;
}
示例14: houghTransform
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
private void houghTransform () {
//Update progress bar string with current task
if(isGUI) publish("Performing full Hough transform...");
IJ.showStatus("Performing full Hough transform...");
//Build an array to store the result from each thread
final Thread[] threads = newThreadArray();
//Create an atomic integer counter that each thread can use to count through the radii
final AtomicInteger ai = new AtomicInteger(radiusMin);
final AtomicInteger progress = new AtomicInteger(0);
final AtomicInteger lastProgress = new AtomicInteger(0);
//Create an array to store the Hough values
houghValues = new int[width][height][depth];
//Create a variable for storing the total progress possible (100 = complete)
//Nute depth is devided by nCPUs, therefore depth*nCPUs/nCPUs = depth
double totalProgress = height*depth/100;
//Build a thread for as many CPUs as are available to the JVM
for (ithread = 0; ithread < threads.length; ithread++) {
// Concurrently run in as many threads as CPUs
threads[ithread] = new Thread() {
{ setPriority(Thread.NORM_PRIORITY); }
@Override
public void run() {
//Divide the radius tasks across the cores available
int currentProgress = 0;
for (int radius = ai.getAndAdd(radiusInc); radius <= radiusMax; radius = ai.getAndAdd(radiusInc)) {
int indexR=(radius-radiusMin)/radiusInc;
//For a given radius, transform each pixel in a circle, and add-up the votes
for(int y = 1; y < height-1; y++) {
//Increment the progress counter, and submit the current progress status
progress.getAndAdd(1);
//Calculate the current progress value
currentProgress = Math.round((float) (progress.get()/totalProgress));
//There is a significant time penalty for progress updates, so only update if needed
if(currentProgress > lastProgress.get()){ //7.8s with if, 8.7s without if, 7.8s with no progress update, 8.7s with delay between GUI updates
if(isGUI && currentProgress <= 100) setProgress(currentProgress);
IJ.showProgress(currentProgress, 100);
lastProgress.set(currentProgress);
}
//Check for interrupt
if(cancelThread) return;
for(int x = 1; x < width-1; x++) {
if( imageValues[(x+offx)+(y+offy)*fullWidth] != 0 ) {// Edge pixel found
for(int i = 0; i < lutSize; i++) {
int a = x + lut[1][i][indexR];
int b = y + lut[0][i][indexR];
if((b >= 0) & (b < height) & (a >= 0) & (a < width)) {
houghValues[a][b][indexR] += 1;
}
}
}
}
}
}
}
};
}
startAndJoin(threads);
}
示例15: forEachAffected
import java.util.concurrent.atomic.AtomicInteger; //导入方法依赖的package包/类
@Override
public void forEachAffected(L2Character activeChar, L2Object target, Skill skill, Consumer<? super L2Object> action)
{
final IAffectObjectHandler affectObject = AffectObjectHandler.getInstance().getHandler(skill.getAffectObject());
final double headingAngle = Util.convertHeadingToDegree(activeChar.getHeading());
final int fanStartAngle = skill.getFanRange()[1];
final int fanRadius = skill.getFanRange()[2];
final int fanAngle = skill.getFanRange()[3];
final double fanHalfAngle = fanAngle / 2; // Half left and half right.
final int affectLimit = skill.getAffectLimit();
// Target checks.
final AtomicInteger affected = new AtomicInteger(0);
final Predicate<L2Character> filter = c ->
{
if ((affectLimit > 0) && (affected.get() >= affectLimit))
{
return false;
}
if (c.isDead())
{
return false;
}
if (Math.abs(Util.calculateAngleFrom(activeChar, c) - (headingAngle + fanStartAngle)) > fanHalfAngle)
{
return false;
}
if ((affectObject != null) && !affectObject.checkAffectedObject(activeChar, c))
{
return false;
}
if (!GeoData.getInstance().canSeeTarget(activeChar, c))
{
return false;
}
affected.incrementAndGet();
return true;
};
// Add object of origin since its skipped in the forEachVisibleObjectInRange method.
if (target.isCharacter() && filter.test((L2Character) target))
{
action.accept(target);
}
// Check and add targets.
L2World.getInstance().forEachVisibleObjectInRange(activeChar, L2Character.class, fanRadius, c ->
{
if (filter.test(c))
{
action.accept(c);
}
});
}