Java Code Examples for java.util.concurrent.atomic.AtomicLong.incrementAndGet()

The following are Jave code examples for showing how to use incrementAndGet() of the java.util.concurrent.atomic.AtomicLong class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Jaffree   File: FFmpegTest.java   Source Code and License Vote up 6 votes
@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);
}
 
Example 2
Project: Jaffree   File: FFmpegTest.java   Source Code and License Vote up 6 votes
@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);
}
 
Example 3
Project: fuck_zookeeper   File: ReferenceCountedACLCache.java   Source Code and License Vote up 6 votes
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();
    }
}
 
Example 4
Project: RxJava3-preview   File: ObservableAmbTest.java   Source Code and License Vote up 6 votes
@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());
}
 
Example 5
Project: ZooKeeper   File: ReferenceCountedACLCache.java   Source Code and License Vote up 6 votes
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();
    }
}
 
Example 6
Project: datarouter   File: MapTool.java   Source Code and License Vote up 6 votes
@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));
}
 
Example 7
Project: https-github.com-apache-zookeeper   File: ReferenceCountedACLCache.java   Source Code and License Vote up 6 votes
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();
    }
}
 
Example 8
Project: Elasticsearch   File: DistributedTranslog.java   Source Code and License Vote up 6 votes
/**
 * 
 * @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();
    }
}
 
Example 9
Project: reactive-grpc   File: BackpressureIntegrationTest.java   Source Code and License Vote up 5 votes
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);
}
 
Example 10
Project: reactive-grpc   File: BackpressureIntegrationTest.java   Source Code and License Vote up 5 votes
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);
}
 
Example 11
Project: elasticsearch_my   File: MockRepository.java   Source Code and License Vote up 5 votes
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;
}
 
Example 12
Project: elasticsearch_my   File: TestAmazonS3.java   Source Code and License Vote up 5 votes
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;
}
 
Example 13
Project: openjdk-jdk10   File: Invoke.java   Source Code and License Vote up 5 votes
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");
}
 
Example 14
Project: javalin   File: TestCustomJetty.java   Source Code and License Vote up 5 votes
@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();
}
 
Example 15
Project: Bytecoder   File: TArrayListTest.java   Source Code and License Vote up 5 votes
@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);
}
 
Example 16
Project: Jaffree   File: FrameIOTest.java   Source Code and License Vote up 4 votes
@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);
}
 
Example 17
Project: elasticsearch_my   File: LongGCDisruptionTest.java   Source Code and License Vote up 4 votes
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();
    }
}
 
Example 18
Project: elasticsearch_my   File: LongGCDisruptionTest.java   Source Code and License Vote up 4 votes
/**
 * 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);
    }
}
 
Example 19
Project: opentsdb-rpc-kafka   File: KafkaStorageExceptionHandler.java   Source Code and License Vote up 4 votes
@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();
    }
  }
}
 
Example 20
Project: wamp2spring   File: IdGenerator.java   Source Code and License Vote up 3 votes
/**
 * Creates new linear identification number from the provided parameter.
 * <p>
 * Used for session scope and router scope ids
 *
 * @param longValue start address of the identification number. Next number will be
 * this value plus 1
 * @return new id
 */
public static long newLinearId(AtomicLong longValue) {
	long candiateId = longValue.incrementAndGet();
	if (candiateId > IdGenerator.MAX) {
		longValue.set(1L);
		candiateId = longValue.longValue();
	}
	return candiateId;
}