本文整理汇总了Java中java.util.concurrent.atomic.AtomicLong类的典型用法代码示例。如果您正苦于以下问题:Java AtomicLong类的具体用法?Java AtomicLong怎么用?Java AtomicLong使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AtomicLong类属于java.util.concurrent.atomic包,在下文中一共展示了AtomicLong类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doTest
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
private static void doTest(int nThreads) throws InterruptedException {
Thread[] aThreads = new Thread[nThreads];
final AtomicLong atl = new AtomicLong();
for (int i = 0; i < nThreads; i++) {
aThreads[i] = new RunnerThread(atl, 1L << (8 * i));
}
for (int i = 0; i < nThreads; i++) {
aThreads[i].start();
}
for (int i = 0; i < nThreads; i++) {
aThreads[i].join();
}
}
示例2: addCancel
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
/**
* Atomically adds the positive value n to the requested value in the AtomicLong and
* caps the result at Long.MAX_VALUE and returns the previous value and
* considers Long.MIN_VALUE as a cancel indication (no addition then).
* @param requested the AtomicLong holding the current requested value
* @param n the value to add, must be positive (not verified)
* @return the original value before the add
*/
public static long addCancel(AtomicLong requested, long n) {
for (;;) {
long r = requested.get();
if (r == Long.MIN_VALUE) {
return Long.MIN_VALUE;
}
if (r == Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
long u = addCap(r, n);
if (requested.compareAndSet(r, u)) {
return r;
}
}
}
示例3: runSimpleQuery
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
public static <T extends ImmutableTrade> void runSimpleQuery(List<T> immutableTrades) {
Comparator<ImmutableTrade> comparator = Comparator.comparing(ImmutableTrade::getExchangeRate);
Predicate<ImmutableTrade> predicate = t -> t.getCurrency1().equalsIgnoreCase("GBP") &&
t.getCurrency2().equalsIgnoreCase("USD") &&
t.getBuySell().equalsIgnoreCase("Buy");
final AtomicLong ignore = new AtomicLong(0);
int n = 10;
System.out.println("Running a filter and sort on the trades (" + n + " times)");
long start = System.nanoTime();
for (int i = 0; i < n; i++) {
System.gc();
immutableTrades.stream()
.filter(predicate)
.sorted(comparator)
.limit(10)
.forEach(p -> ignore.set(p.getId()));
}
System.out.println("ignore: " + ignore.get());
System.out.printf("Query time = %.3f seconds%n%n", (System.nanoTime() - start) / 1e9);
}
示例4: doCommits
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
private void doCommits(String tableName, final List<com.alicloud.tablestore.adaptor.struct.OPut> puts) throws IOException {
boolean flushSuccessfully = false;
try {
otsProxy.putMultiple(tableName, puts);
flushSuccessfully = true;
} finally {
if (!flushSuccessfully && !getClearBufferOnFail(tableName)) {
ArrayList<com.alicloud.tablestore.adaptor.struct.OPut> tableWriteBuffer = getTableWriteBuffer(tableName);
synchronized (tableWriteBuffer) {
AtomicLong currentBufferSize = getTableCurrentBufferSize(tableName);
for (com.alicloud.tablestore.adaptor.struct.OPut put : puts) {
tableWriteBuffer.add(put);
currentBufferSize.addAndGet(put.getWritableSize());
}
}
}
}
}
示例5: CacheManager
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
private CacheManager(final File cacheDir, final long sizeLimit, final int countLimit) {
this.cacheDir = cacheDir;
this.sizeLimit = sizeLimit;
this.countLimit = countLimit;
cacheSize = new AtomicLong();
cacheCount = new AtomicInteger();
mThread = new Thread(new Runnable() {
@Override
public void run() {
int size = 0;
int count = 0;
final File[] cachedFiles = cacheDir.listFiles();
if (cachedFiles != null) {
for (File cachedFile : cachedFiles) {
size += cachedFile.length();
count += 1;
lastUsageDates.put(cachedFile, cachedFile.lastModified());
}
cacheSize.getAndAdd(size);
cacheCount.getAndAdd(count);
}
}
});
mThread.start();
}
示例6: deserialze
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
final JSONLexer lexer = parser.getLexer();
Long longObject;
if (lexer.token() == JSONToken.LITERAL_INT) {
long longValue = lexer.longValue();
lexer.nextToken(JSONToken.COMMA);
longObject = Long.valueOf(longValue);
} else {
Object value = parser.parse();
if (value == null) {
return null;
}
longObject = TypeUtils.castToLong(value);
}
if (clazz == AtomicLong.class) {
return (T) new AtomicLong(longObject.longValue());
}
return (T) longObject;
}
示例7: waitForCounterBoolean
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
private boolean waitForCounterBoolean(final AtomicLong ctr, final long oldval, final long newval,
long timems, boolean failIfTimeout) throws Exception {
long timeWaited = TEST_UTIL.waitFor(timems, 10, failIfTimeout,
new Waiter.Predicate<Exception>() {
@Override
public boolean evaluate() throws Exception {
return (ctr.get() >= newval);
}
});
if( timeWaited > 0) {
// when not timed out
assertEquals(newval, ctr.get());
}
return true;
}
示例8: emitItem
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
private void emitItem(GroupState<K, T> groupState, Object item) {
Queue<Object> q = groupState.buffer;
AtomicLong keyRequested = groupState.requested;
REQUESTED.decrementAndGet(this);
if (keyRequested == null || keyRequested.get() <= 0 || !(q == null || q.isEmpty())) {
q.add(item);
BUFFERED_COUNT.incrementAndGet(this);
if (groupState.count.getAndIncrement() == 0) {
pollQueue(groupState);
}
} else {
nl.accept(groupState.getObserver(), item);
if (keyRequested.get() != Long.MAX_VALUE) {
keyRequested.decrementAndGet();
}
}
requestMoreIfNecessary();
}
示例9: addUsage
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
public synchronized void addUsage(Long acl) {
if (acl == OPEN_UNSAFE_ACL_ID) {
return;
}
if (!longKeyMap.containsKey(acl)) {
LOG.info("Ignoring acl " + acl + " as it does not exist in the cache");
return;
}
AtomicLong count = referenceCounter.get(acl);
if (count == null) {
referenceCounter.put(acl, new AtomicLongWithEquals(1));
} else {
count.incrementAndGet();
}
}
示例10: waitForChange_runWithRealmThread
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
@Test
public void waitForChange_runWithRealmThread() throws InterruptedException {
final CountDownLatch bgRealmStarted = new CountDownLatch(1);
final CountDownLatch bgRealmFished = new CountDownLatch(1);
final AtomicBoolean bgRealmChangeResult = new AtomicBoolean(false);
final AtomicLong bgRealmResultSize = new AtomicLong(0);
RealmThread thread = new RealmThread(realmConfig, new RealmThread.RealmRunnable() {
@Override
public void run(Realm realm) {
bgRealmStarted.countDown();
bgRealmChangeResult.set(realm.waitForChange());
bgRealmResultSize.set(realm.where(AllTypes.class).count());
realm.close();
bgRealmFished.countDown();
}
});
thread.start();
TestHelper.awaitOrFail(bgRealmStarted);
populateTestRealm();
TestHelper.awaitOrFail(bgRealmFished);
assertTrue(bgRealmChangeResult.get());
assertEquals(TEST_DATA_SIZE, bgRealmResultSize.get());
}
示例11: deserialze
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
Long longObject;
JSONLexer lexer = parser.getLexer();
if (lexer.token() == 2) {
long longValue = lexer.longValue();
lexer.nextToken(16);
longObject = Long.valueOf(longValue);
} else {
Object value = parser.parse();
if (value == null) {
return null;
}
longObject = TypeUtils.castToLong(value);
}
if (clazz == AtomicLong.class) {
return new AtomicLong(longObject.longValue());
}
return longObject;
}
示例12: testSimulateHighVolumeWithBoxedData
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
/**
* Creates and destroys lots of records in such a way that some may end up getting past
* the eden space.
*/
@Test
@Ignore
public void testSimulateHighVolumeWithBoxedData() throws InterruptedException {
BlockingQueue<Iterable<Record>> queue = new ArrayBlockingQueue<>(QUEUE_DEPTH);
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
try {
timerStart = new AtomicLong(System.currentTimeMillis());
processed = new AtomicLong(0);
IntStream.range(0, 10).forEach(i -> pool.execute(() -> produce(queue, this::randomiseObjects)));
IntStream.range(0, 8).forEach(i -> pool.execute(() -> consume(queue, this::readObjects)));
} finally {
pool.shutdown();
pool.awaitTermination(3, TimeUnit.MINUTES);
}
}
示例13: ensureSyncComplete
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
public void ensureSyncComplete(int blockIndex) {
final AtomicLong noSyncLength = noSyncLengthMap.get(blockIndex);
if (noSyncLength != null && noSyncLength.get() > 0) {
// sync to store
if (syncRunning) {
// wait for sync
parkThreadList.add(Thread.currentThread());
while (true) {
LockSupport.parkNanos(WAIT_SYNC_NANO);
if (!syncRunning) break;
}
}
// sync once, make sure data has been synced.
syncRunning = true;
syncRunnable.run();
}
}
示例14: write
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
@Test
public void write() throws IOException {
final DownloadOutputStream outputStream = mock(DownloadOutputStream.class);
doReturn(outputStream).when(multiPointOutputStream).outputStream(anyInt());
multiPointOutputStream.syncRunning = true;
final byte[] bytes = new byte[6];
multiPointOutputStream.noSyncLengthMap.put(1, new AtomicLong());
multiPointOutputStream.write(1, bytes, 6);
verify(multiPointOutputStream).write(1, bytes, 6);
multiPointOutputStream.noSyncLengthMap.put(2, new AtomicLong());
multiPointOutputStream.write(2, bytes, 16);
verify(multiPointOutputStream).write(2, bytes, 16);
assertThat(multiPointOutputStream.allNoSyncLength.get()).isEqualTo(22);
assertThat(multiPointOutputStream.noSyncLengthMap.get(1).get()).isEqualTo(6);
assertThat(multiPointOutputStream.noSyncLengthMap.get(2).get()).isEqualTo(16);
}
示例15: initialize
import java.util.concurrent.atomic.AtomicLong; //导入依赖的package包/类
public void initialize(){
activeCompanyCount = companies.getCompanyCount();
activeSecurityCount = SecurityHandler.getSecurityNum(myCustomerCount);
industryCount = industries.getMaxKey();
sectorCount = sectors.getMaxKey();
startFromCompany = companies.generateCompId();
maxActivePrePopulatedTradeID = (int)(( hoursOfInitialTrades * EGenDate.SecondsPerHour * ( activeCustomerCount / scaleFactor )) * TPCEConstants.AbortTrade / 100 );
currentTradeID = new AtomicLong(maxActivePrePopulatedTradeID + 1);
startTime = EGenDate.getDateFromTime(
TPCEConstants.initialTradePopulationBaseYear,
TPCEConstants.initialTradePopulationBaseMonth,
TPCEConstants.initialTradePopulationBaseDay,
TPCEConstants.initialTradePopulationBaseHour,
TPCEConstants.initialTradePopulationBaseMinute,
TPCEConstants.initialTradePopulationBaseSecond,
TPCEConstants.initialTradePopulationBaseFraction );
}