本文整理汇总了Java中java.util.concurrent.atomic.AtomicLong.incrementAndGet方法的典型用法代码示例。如果您正苦于以下问题:Java AtomicLong.incrementAndGet方法的具体用法?Java AtomicLong.incrementAndGet怎么用?Java AtomicLong.incrementAndGet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.atomic.AtomicLong
的用法示例。
在下文中一共展示了AtomicLong.incrementAndGet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testProgress
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void testProgress() throws Exception {
Path tempDir = Files.createTempDirectory("jaffree");
Path outputPath = tempDir.resolve("test.mkv");
final AtomicLong counter = new AtomicLong();
ProgressListener listener = new ProgressListener() {
@Override
public void onProgress(FFmpegProgress progress) {
counter.incrementAndGet();
}
};
FFmpegResult result = FFmpeg.atPath(BIN)
.addInput(UrlInput.fromPath(SMALL_FLV))
.addOutput(UrlOutput.toPath(outputPath))
.setProgressListener(listener)
.execute();
Assert.assertNotNull(result);
Assert.assertTrue(counter.get() > 0);
}
示例2: testProgress2
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void testProgress2() throws Exception {
Path tempDir = Files.createTempDirectory("jaffree");
Path outputPath = tempDir.resolve("test.flv");
final AtomicLong counter = new AtomicLong();
ProgressListener listener = new ProgressListener() {
@Override
public void onProgress(FFmpegProgress progress) {
counter.incrementAndGet();
}
};
FFmpegResult result = FFmpeg.atPath(BIN)
.addInput(UrlInput.fromPath(SMALL_MP4))
.addOutput(UrlOutput.toPath(outputPath))
.setProgressListener(listener)
.execute();
Assert.assertNotNull(result);
Assert.assertTrue(counter.get() > 0);
}
示例3: 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();
}
}
示例4: testSubscriptionOnlyHappensOnce
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testSubscriptionOnlyHappensOnce() throws InterruptedException {
final AtomicLong count = new AtomicLong();
Consumer<Disposable> incrementer = new Consumer<Disposable>() {
@Override
public void accept(Disposable s) {
count.incrementAndGet();
}
};
//this aync stream should emit first
Observable<Integer> o1 = Observable.just(1).doOnSubscribe(incrementer)
.delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
//this stream emits second
Observable<Integer> o2 = Observable.just(1).doOnSubscribe(incrementer)
.delay(100, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation());
TestObserver<Integer> ts = new TestObserver<Integer>();
Observable.ambArray(o1, o2).subscribe(ts);
ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
ts.assertNoErrors();
assertEquals(2, count.get());
}
示例5: testGetByNullableKeyValueMapper
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void testGetByNullableKeyValueMapper(){
List<String> strings = Arrays.asList("aaa", "b", "ca", "eeee", "ca");
AtomicLong counterA = new AtomicLong(0);
Function<String,String> valueMapper = str -> {
if(str.contains("a")){
return counterA.incrementAndGet() + "a";
}
if(str.contains("b")){
return "b";
}
return null;
};
Map<Integer,String> containsByLength = MapTool.getByNullable(strings, String::length, valueMapper);
Assert.assertEquals(containsByLength.keySet(), Arrays.asList(3, 1, 2, 4));
Assert.assertEquals(containsByLength.values(), Arrays.asList("1a", "b", "3a", null));
}
示例6: writeOperation
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
/**
*
* @param operation
* @return
* @throws IOException
*/
public Tuple<Future<DLSN>, Tuple<BytesReference, Long>> writeOperation(Translog.Operation operation, AtomicLong txid) throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
try (ReleasableLock lock = writeLock.acquire()) {
Future<DLSN> writeResult = null;
out.writeByte(operation.opType().id());
operation.writeTo(out);
BytesReference bytes = out.bytes();
LogRecord logRecord = new LogRecord(txid.incrementAndGet(), bytes.toBytes());
writeResult = logWriter.write(logRecord);
sizeInBytes += (20 + logRecord.getPayload().length);
++ numOperations;
return new Tuple<Future<DLSN>, Tuple<BytesReference, Long>>(writeResult, new Tuple<BytesReference, Long>(bytes, txid.get()));
} catch (TransactionIdOutOfOrderException e) {
throw e;
} finally {
out.close();
}
}
示例7: updateNumberOfWaits
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
private static void updateNumberOfWaits(AtomicLong start, AtomicLong maxTime) {
Long now = System.currentTimeMillis();
Long startValue = start.get();
if (startValue != 0 && now - startValue > 1000) {
maxTime.incrementAndGet();
}
start.set(now);
}
示例8: incrementAndGet
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
private long incrementAndGet(String path) {
AtomicLong value = accessCounts.get(path);
if (value == null) {
value = accessCounts.putIfAbsent(path, new AtomicLong(1));
}
if (value != null) {
return value.incrementAndGet();
}
return 1;
}
示例9: main
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
public static void main(String[] args) {
try {
final AtomicLong count = new AtomicLong(0);
ExecutorService fixed = Executors.newFixedThreadPool(5);
class Inc implements Callable<Long> {
public Long call() throws Exception {
Thread.sleep(200); // Catch IE from possible cancel
return count.incrementAndGet();
}
}
List<Inc> tasks = Arrays.asList(new Inc(), new Inc(), new Inc());
List<Future<Long>> futures = fixed.invokeAll(tasks);
check(futures.size() == tasks.size());
check(count.get() == tasks.size());
long gauss = 0;
for (Future<Long> future : futures) gauss += future.get();
check(gauss == ((tasks.size()+1)*tasks.size())/2);
ExecutorService single = Executors.newSingleThreadExecutor();
long save = count.get();
check(single.invokeAny(tasks) == save + 1);
check(count.get() == save + 1);
fixed.shutdown();
single.shutdown();
} catch (Throwable t) { unexpected(t); }
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Error("Some tests failed");
}
示例10: test_embeddedServer_withHandlerChain
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void test_embeddedServer_withHandlerChain() throws Exception {
AtomicLong logCount = new AtomicLong(0);
RequestLog requestLog = (request, response) -> logCount.incrementAndGet();
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
StatisticsHandler handlerChain = new StatisticsHandler();
handlerChain.setHandler(requestLogHandler);
Javalin app = Javalin.create()
.port(0)
.embeddedServer(new EmbeddedJettyFactory(() -> {
Server server = new Server();
server.setHandler(handlerChain);
return server;
}))
.get("/", ctx -> ctx.result("Hello World"))
.start();
String origin = "http://localhost:" + app.port();
int requests = 10;
for (int i = 0; i < requests; i++) {
assertThat(Unirest.get(origin + "/").asString().getBody(), is("Hello World"));
assertThat(Unirest.get(origin + "/not_there").asString().getStatus(), is(404));
}
assertThat(handlerChain.getDispatched(), is(requests * 2));
assertThat(handlerChain.getResponses2xx(), is(requests));
assertThat(handlerChain.getResponses4xx(), is(requests));
assertThat(logCount.get(), is((long) (requests * 2)));
app.stop();
}
示例11: testIterator
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void testIterator() {
ArrayList theList = new ArrayList();
theList.add("A");
theList.add("B");
AtomicLong theLong = new AtomicLong(0);
for (Object a : theList) {
theLong.incrementAndGet();
}
Assert.assertEquals(2, theLong.get(), 0);
}
示例12: dumpFrames
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Test
public void dumpFrames() throws Exception {
final Path tempDir = Files.createTempDirectory("jaffree");
System.out.println("Will write to " + tempDir);
final AtomicLong trackCounter = new AtomicLong();
final AtomicLong frameCounter = new AtomicLong();
FrameConsumer consumer = new FrameConsumer() {
@Override
public void consumeStreams(List<Stream> tracks) {
trackCounter.set(tracks.size());
}
@Override
public void consume(Frame frame) {
if (frame == null) {
return;
}
long n = frameCounter.incrementAndGet();
String filename = String.format("frame%05d.png", n);
try {
boolean written = ImageIO.write(frame.getImage(), "png", tempDir.resolve(filename).toFile());
Assert.assertTrue(written);
System.out.println(filename);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
FFmpegResult result = FFmpeg.atPath(BIN)
.addInput(
UrlInput.fromPath(VIDEO_MP4)
.setDuration(1, TimeUnit.SECONDS)
)
.addOutput(
FrameOutput.withConsumer(consumer)
.extractVideo(true)
.extractAudio(false)
)
.execute();
Assert.assertNotNull(result);
Assert.assertEquals(1, trackCounter.get());
Assert.assertTrue(frameCounter.get() > 10);
}
示例13: testBlockingTimeout
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
public void testBlockingTimeout() throws Exception {
final String nodeName = "test_node";
LongGCDisruption disruption = new LongGCDisruption(random(), nodeName) {
@Override
protected Pattern[] getUnsafeClasses() {
return new Pattern[]{
Pattern.compile(LockedExecutor.class.getSimpleName())
};
}
@Override
protected long getStoppingTimeoutInMillis() {
return 100;
}
};
final AtomicBoolean stop = new AtomicBoolean();
final CountDownLatch underLock = new CountDownLatch(1);
final CountDownLatch pauseUnderLock = new CountDownLatch(1);
final LockedExecutor lockedExecutor = new LockedExecutor();
final AtomicLong ops = new AtomicLong();
try {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
// at least one locked and one none lock thread
final boolean lockedExec = (i < 9 && randomBoolean()) || i == 0;
threads[i] = new Thread(() -> {
while (stop.get() == false) {
if (lockedExec) {
lockedExecutor.executeLocked(() -> {
try {
underLock.countDown();
ops.incrementAndGet();
pauseUnderLock.await();
} catch (InterruptedException e) {
}
});
} else {
ops.incrementAndGet();
}
}
});
threads[i].setName("[" + nodeName + "][" + i + "]");
threads[i].start();
}
// make sure some threads are under lock
underLock.await();
RuntimeException e = expectThrows(RuntimeException.class, disruption::startDisrupting);
assertThat(e.getMessage(), containsString("stopping node threads took too long"));
} finally {
stop.set(true);
pauseUnderLock.countDown();
}
}
示例14: testNotBlockingUnsafeStackTraces
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
/**
* Checks that a GC disruption never blocks threads while they are doing something "unsafe"
* but does keep retrying until all threads can be safely paused
*/
public void testNotBlockingUnsafeStackTraces() throws Exception {
final String nodeName = "test_node";
LongGCDisruption disruption = new LongGCDisruption(random(), nodeName) {
@Override
protected Pattern[] getUnsafeClasses() {
return new Pattern[]{
Pattern.compile(LockedExecutor.class.getSimpleName())
};
}
};
final AtomicBoolean stop = new AtomicBoolean();
final LockedExecutor lockedExecutor = new LockedExecutor();
final AtomicLong ops = new AtomicLong();
try {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int iter = 0; stop.get() == false; iter++) {
if (iter % 2 == 0) {
lockedExecutor.executeLocked(() -> {
Thread.yield(); // give some chance to catch this stack trace
ops.incrementAndGet();
});
} else {
Thread.yield(); // give some chance to catch this stack trace
ops.incrementAndGet();
}
}
});
threads[i].setName("[" + nodeName + "][" + i + "]");
threads[i].start();
}
// make sure some threads are under lock
disruption.startDisrupting();
long first = ops.get();
assertThat(lockedExecutor.lock.isLocked(), equalTo(false)); // no threads should own the lock
Thread.sleep(100);
assertThat(ops.get(), equalTo(first));
disruption.stopDisrupting();
assertBusy(() -> assertThat(ops.get(), greaterThan(first)));
} finally {
stop.set(true);
}
}
示例15: handleError
import java.util.concurrent.atomic.AtomicLong; //导入方法依赖的package包/类
@Override
public void handleError(final IncomingDataPoint dp,
final Exception exception) {
KafkaRequeueTopic type = KafkaRequeueTopic.DEFAULT;
try {
if (dp == null) {
throw new IllegalArgumentException("Unable to reque a null data point.");
}
if (dp instanceof Metric) {
type = KafkaRequeueTopic.RAW;
} else if (dp instanceof Aggregate &&
Strings.isNullOrEmpty(((Aggregate) dp).getInterval())) {
type = KafkaRequeueTopic.PREAGGREGATE;
} else if (dp instanceof Aggregate) {
type = KafkaRequeueTopic.ROLLUP;
} else if (dp instanceof Histogram) {
type = KafkaRequeueTopic.HISTOGRAM;
}
String topic = topic_name_map.get(type);
if (Strings.isNullOrEmpty(topic)) {
type = KafkaRequeueTopic.DEFAULT;
topic = topic_name_map.get(type);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Routing SEH message " + dp + " to topic: " + topic);
}
int hash = dp.getMetric().hashCode() + Objects.hashCode(dp.getTags());
final KeyedMessage<String, byte[]> data =
new KeyedMessage<String, byte[]>(topic,
Integer.toString(Math.abs(hash)),
JSON.serializeToBytes(dp));
producer.send(data);
final AtomicLong requeued = topic_requeued_counters.get(type);
if (requeued != null) {
requeued.incrementAndGet();
}
} catch (final Exception ex) {
LOG.error("Unexpected exception publishing data", ex);
final AtomicLong requeue_ex = topic_requeued_exception_counters
.get(type);
if (requeue_ex != null) {
requeue_ex.incrementAndGet();
}
}
}