Example usage for java.util.concurrent.atomic AtomicLong get

List of usage examples for java.util.concurrent.atomic AtomicLong get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicLong get.

Prototype

public final long get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:ubicrypt.core.util.OnSubscribeInputStreamTest.java

@Test
public void testBig() throws Exception {
    final AtomicLong count = new AtomicLong();
    final CountDownLatch cd = new CountDownLatch(1);
    Observable/*from ww  w  . j a  va2 s .  co  m*/
            .create(new OnSubscribeInputStream(
                    new ByteArrayInputStream(StringUtils.repeat('a', 2 << 16).getBytes()), 1 << 16))
            .doOnCompleted(cd::countDown).subscribe(next -> count.addAndGet(next.length));
    assertThat(cd.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(count.get()).isEqualTo(2 << 16);
}

From source file:ubicrypt.core.util.OnSubscribeInputStreamTest.java

@Test
public void testBig2() throws Exception {
    final AtomicLong count = new AtomicLong();
    final CountDownLatch cd = new CountDownLatch(1);
    Observable/*w w w  .  j  ava  2  s . c  om*/
            .create(new OnSubscribeInputStream(
                    new ByteArrayInputStream(StringUtils.repeat('a', (2 << 16) - 1).getBytes()), 1 << 16))
            .doOnCompleted(cd::countDown).subscribe(next -> count.addAndGet(next.length));
    assertThat(cd.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(count.get()).isEqualTo((2 << 16) - 1);
}

From source file:org.apache.hadoop.hbase.regionserver.TestSplitLogWorker.java

private void waitForCounter(AtomicLong ctr, long oldval, long newval, long timems) throws Exception {
    assertTrue("ctr=" + ctr.get() + ", oldval=" + oldval + ", newval=" + newval,
            waitForCounterBoolean(ctr, oldval, newval, timems));
}

From source file:ubicrypt.core.UtilsTest.java

private void write(final int size) throws InterruptedException, IOException {
    final Path target = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] bytes = new byte[size];
    new Random().nextBytes(bytes);

    final AtomicLong length = new AtomicLong(0);
    final CountDownLatch cd = new CountDownLatch(1);
    Utils.write(target, new ByteArrayInputStream(bytes)).subscribe(sizef -> {
        length.set(sizef);/* w  w w .j  a  v  a  2s .co m*/
    }, Throwable::printStackTrace, () -> {
        cd.countDown();
    });
    if (!cd.await(2, TimeUnit.SECONDS)) {
        Assertions.fail("not arrived completed");
    }
    assertThat(length.get()).isEqualTo(bytes.length);
    assertThat(Files.readAllBytes(target)).isEqualTo(bytes);
    Files.delete(target);
}

From source file:org.apache.flink.monitor.trackers.HistogramTaskTracker.java

/**
 * Set the histogram head to a relative size given in percent of the size of
 * the local histogram. The tau value is determined by computing the average
 * and multiplying it by this.adaptiveTau.
 *//*ww  w  . jav a  2 s.  co  m*/
private void setAdaptiveHeadAndTau() {
    if (this.adaptiveSummarySizeInPercent > 0) {
        this.summarySize = (int) (this.topKMap.size() * this.adaptiveSummarySizeInPercent / 100);
    }

    if (this.adaptiveTau > 0) {
        long count = 0;
        for (AtomicLong f : this.topKMap.values()) {
            count += f.get();
        }
        if (!this.topKMap.isEmpty()) {
            int average = (int) (count / this.topKMap.size());
            this.tau = average * this.adaptiveTau;
        }
    }
}

From source file:org.apache.drill.exec.expr.fn.registry.LocalFunctionRegistry.java

/**
 * Registers all functions present in {@link DrillOperatorTable},
 * also sets local registry version used at the moment of registering.
 *
 * @param operatorTable drill operator table
 */// www . j  a  va 2 s .c  o  m
public void register(DrillOperatorTable operatorTable) {
    AtomicLong versionHolder = new AtomicLong();
    final Map<String, Collection<DrillFuncHolder>> registeredFunctions = registryHolder
            .getAllFunctionsWithHolders(versionHolder).asMap();
    operatorTable.setFunctionRegistryVersion(versionHolder.get());
    registerOperatorsWithInference(operatorTable, registeredFunctions);
    registerOperatorsWithoutInference(operatorTable, registeredFunctions);
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

protected void assertCounterMakesProgress(final AtomicLong counter, int timeout, TimeUnit unit)
        throws InterruptedException {
    final long initial = counter.get();
    within(timeout, unit, new Task() {
        public void run() throws Exception {
            assertTrue(initial < counter.get());
        }//from   ww  w.j a v a2  s. c o m
    });
}

From source file:com.netflix.curator.framework.imps.TestFrameworkBackground.java

@Test
public void testRetries() throws Exception {
    final int SLEEP = 1000;
    final int TIMES = 5;

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryNTimes(TIMES, SLEEP));
    try {//from  w  ww .j  a v a  2 s.  com
        client.start();
        client.getZookeeperClient().blockUntilConnectedOrTimedOut();

        final CountDownLatch latch = new CountDownLatch(TIMES);
        final List<Long> times = Lists.newArrayList();
        final AtomicLong start = new AtomicLong(System.currentTimeMillis());
        ((CuratorFrameworkImpl) client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() {
            @Override
            public void listen(OperationAndData<?> data) {
                if (data.getOperation().getClass().getName().contains("CreateBuilderImpl")) {
                    long now = System.currentTimeMillis();
                    times.add(now - start.get());
                    start.set(now);
                    latch.countDown();
                }
            }
        };

        server.stop();
        client.create().inBackground().forPath("/one");

        latch.await();

        for (long elapsed : times.subList(1, times.size())) // first one isn't a retry
        {
            Assert.assertTrue(elapsed >= SLEEP, elapsed + ": " + times);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:org.apache.hadoop.hbase.client.SpeculativeMutater.java

public Boolean mutate(final long waitToSendFailover, final long waitToSendFailoverWithException,
        final HBaseTableFunction<Void> function, final HTableInterface primaryTable,
        final Collection<HTableInterface> failoverTables, final AtomicLong lastPrimaryFail,
        final int waitTimeFromLastPrimaryFail) {
    ExecutorCompletionService<Boolean> exeS = new ExecutorCompletionService<Boolean>(exe);

    ArrayList<Callable<Boolean>> callables = new ArrayList<Callable<Boolean>>();

    final AtomicBoolean isPrimarySuccess = new AtomicBoolean(false);
    final long startTime = System.currentTimeMillis();
    final long lastPrimaryFinalFail = lastPrimaryFail.get();

    if (System.currentTimeMillis() - lastPrimaryFinalFail > 5000) {
        callables.add(new Callable<Boolean>() {
            public Boolean call() throws Exception {
                try {
                    LOG.info(" --- CallingPrimary.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(primaryTable);
                    LOG.info(" --- CallingPrimary.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    isPrimarySuccess.set(true);
                    return true;
                } catch (java.io.InterruptedIOException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    lastPrimaryFail.set(System.currentTimeMillis());
                    Thread.currentThread().interrupt();
                }//from  w  w  w.java 2s.  c o m
                return null;
            }
        });
    }

    for (final HTableInterface failoverTable : failoverTables) {
        callables.add(new Callable<Boolean>() {

            public Boolean call() throws Exception {
                long waitToRequest = (System.currentTimeMillis() - lastPrimaryFinalFail > 5000)
                        ? waitToSendFailover - (System.currentTimeMillis() - startTime)
                        : waitToSendFailoverWithException - (System.currentTimeMillis() - startTime);

                LOG.info(" --- waitToRequest:" + waitToRequest + ","
                        + (System.currentTimeMillis() - lastPrimaryFinalFail) + ","
                        + (waitToSendFailover - (System.currentTimeMillis() - startTime)) + ","
                        + (waitToSendFailoverWithException - (System.currentTimeMillis() - startTime)));

                if (waitToRequest > 0) {
                    Thread.sleep(waitToRequest);
                }
                LOG.info(" --- isPrimarySuccess.get():" + isPrimarySuccess.get());
                if (isPrimarySuccess.get() == false) {
                    LOG.info(" --- CallingFailOver.1:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                    function.call(failoverTable);
                    LOG.info(" --- CallingFailOver.2:" + isPrimarySuccess.get() + ", "
                            + (System.currentTimeMillis() - startTime));
                }

                return false;
            }
        });
    }
    try {

        for (Callable<Boolean> call : callables) {
            exeS.submit(call);
        }
        Boolean result = exeS.take().get();
        return result;
    } catch (InterruptedException e) {
        e.printStackTrace();
        LOG.error(e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        LOG.error(e);
    }
    return null;
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.core.DataProcessor.java

private long calculateMetric(@NonNull List<SolutionPerJob> spjList,
        BiConsumer<SolutionPerJob, Double> resultSaver, Consumer<SolutionPerJob> ifEmpty) {
    //to support also parallel stream.
    AtomicLong executionTime = new AtomicLong();

    spjList.forEach(spj -> {/* ww w .  j  a  v a2 s  .  co  m*/
        Pair<Optional<Double>, Long> result = simulateClass(spj);
        executionTime.addAndGet(result.getRight());
        Optional<Double> optionalValue = result.getLeft();
        if (optionalValue.isPresent())
            resultSaver.accept(spj, optionalValue.get());
        else
            ifEmpty.accept(spj);
    });

    return executionTime.get();
}