Example usage for java.util.concurrent.atomic AtomicInteger decrementAndGet

List of usage examples for java.util.concurrent.atomic AtomicInteger decrementAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicInteger decrementAndGet.

Prototype

public final int decrementAndGet() 

Source Link

Document

Atomically decrements the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

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

@Test
public void testSubmitTrue() throws IOException {
    final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false);
    ap.tasksInProgress.incrementAndGet();
    final AtomicInteger ai = new AtomicInteger(1);
    ap.taskCounterPerRegion.put(hri1.getRegionName(), ai);

    final AtomicBoolean checkPoint = new AtomicBoolean(false);
    final AtomicBoolean checkPoint2 = new AtomicBoolean(false);

    Thread t = new Thread() {
        @Override/*from   w w w.j a  va2s. co  m*/
        public void run() {
            Threads.sleep(1000);
            Assert.assertFalse(checkPoint.get()); // TODO: this is timing-dependent
            ai.decrementAndGet();
            ap.tasksInProgress.decrementAndGet();
            checkPoint2.set(true);
        }
    };

    List<Put> puts = new ArrayList<Put>();
    Put p = createPut(1, true);
    puts.add(p);

    ap.submit(DUMMY_TABLE, puts, false, null, false);
    Assert.assertFalse(puts.isEmpty());

    t.start();

    ap.submit(DUMMY_TABLE, puts, true, null, false);
    Assert.assertTrue(puts.isEmpty());

    checkPoint.set(true);
    while (!checkPoint2.get()) {
        Threads.sleep(1);
    }
}

From source file:org.waarp.openr66.protocol.http.rest.test.HttpTestResponseHandler.java

@Override
protected boolean afterDbOptions(Channel channel, RestArgument ra) throws HttpInvalidAuthenticationException {
    HttpTestRestR66Client.count.incrementAndGet();
    boolean newMessage = false;
    AtomicInteger counter = null;
    RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get();
    if (future.getOtherObject() == null) {
        counter = new AtomicInteger();
        future.setOtherObject(counter);/*  ww  w.j a v  a 2  s  .  c o  m*/
        JsonNode node = ra.getDetailedAllowOption();
        if (!node.isMissingNode()) {
            for (JsonNode jsonNode : node) {
                Iterator<String> iterator = jsonNode.fieldNames();
                while (iterator.hasNext()) {
                    String name = iterator.next();
                    if (!jsonNode.path(name).path(RestArgument.REST_FIELD.JSON_PATH.field).isMissingNode()) {
                        break;
                    }
                    if (name.equals(RootOptionsRestMethodHandler.ROOT)) {
                        continue;
                    }
                    counter.incrementAndGet();
                    HttpTestRestR66Client.options(channel, name);
                    newMessage = true;
                }
            }
        }
    }
    if (!newMessage) {
        counter = (AtomicInteger) future.getOtherObject();
        newMessage = counter.decrementAndGet() > 0;
        if (!newMessage) {
            future.setOtherObject(null);
        }
    }
    if (!newMessage) {
        WaarpSslUtility.closingSslChannel(channel);
    }
    return newMessage;
}

From source file:com.milaboratory.core.alignment.KAlignerTest.java

@Test
public void testRandomCorrectnessConcurrent() throws Exception {
    KAlignerParameters p = gParams.clone().setMapperKValue(6).setAlignmentStopPenalty(Integer.MIN_VALUE)
            .setMapperAbsoluteMinScore(2.1f).setMapperMinSeedsDistance(4);
    p.setScoring(new LinearGapAlignmentScoring(NucleotideSequence.ALPHABET,
            ScoringUtils.getSymmetricMatrix(4, -4, 4), -5)).setMaxAdjacentIndels(2);

    KAlignerParameters[] params = new KAlignerParameters[] { p.clone(), p.clone().setFloatingLeftBound(true),
            p.clone().setFloatingRightBound(true),
            p.clone().setFloatingLeftBound(true).setFloatingRightBound(true) };

    RandomDataGenerator rdi = new RandomDataGenerator(new Well19937c(127368647891L));
    final int baseSize = its(400, 2000);
    final int total = its(3000, 30000);
    final int threadCount = 20;
    int i, id;// w  w w  .j  a  v a2  s  .co  m

    final NucleotideMutationModel mutationModel = MutationModels.getEmpiricalNucleotideMutationModel()
            .multiplyProbabilities(2.0);
    mutationModel.reseed(12343L);

    for (final KAlignerParameters parameters : params) {
        final KAligner aligner = new KAligner(parameters);

        final AtomicInteger correct = new AtomicInteger(0), incorrect = new AtomicInteger(0),
                miss = new AtomicInteger(0), scoreError = new AtomicInteger(0), random = new AtomicInteger(0);

        final List<NucleotideSequence> ncs = new ArrayList<>(baseSize);
        for (i = 0; i < baseSize; ++i) {
            NucleotideSequence reference = randomSequence(NucleotideSequence.ALPHABET, rdi, 100, 300);
            ncs.add(reference);
            aligner.addReference(reference);
        }

        final AtomicInteger counter = new AtomicInteger(total);

        Thread[] threads = new Thread[threadCount];

        final AtomicLong time = new AtomicLong(0L);

        final AtomicLong seedCounter = new AtomicLong(1273L);
        for (i = 0; i < threadCount; ++i) {
            threads[i] = new Thread() {
                @Override
                public void run() {
                    long timestamp;
                    //Different seed for different thread.
                    RandomDataGenerator rdi = new RandomDataGenerator(
                            new Well19937c(seedCounter.addAndGet(117L)));
                    while (counter.decrementAndGet() >= 0) {
                        int id = rdi.nextInt(0, baseSize - 1);
                        NucleotideSequence ref = ncs.get(id);
                        int trimRight, trimLeft;
                        boolean addLeft, addRight;

                        if (parameters.isFloatingLeftBound()) {
                            trimLeft = rdi.nextInt(0, ref.size() / 3);
                            addLeft = true;
                        } else {
                            if (rdi.nextInt(0, 1) == 0) {
                                trimLeft = 0;
                                addLeft = true;
                            } else {
                                trimLeft = rdi.nextInt(0, ref.size() / 3);
                                addLeft = false;
                            }
                        }

                        if (parameters.isFloatingRightBound()) {
                            trimRight = rdi.nextInt(0, ref.size() / 3);
                            addRight = true;
                        } else {
                            if (rdi.nextInt(0, 1) == 0) {
                                trimRight = 0;
                                addRight = true;
                            } else {
                                trimRight = rdi.nextInt(0, ref.size() / 3);
                                addRight = false;
                            }
                        }

                        NucleotideSequence subSeq = ref.getRange(trimLeft, ref.size() - trimRight);
                        NucleotideSequence left = addLeft
                                ? randomSequence(NucleotideSequence.ALPHABET, rdi, 10, 30)
                                : EMPTY;
                        NucleotideSequence right = addRight
                                ? randomSequence(NucleotideSequence.ALPHABET, rdi, 10, 30)
                                : EMPTY;

                        int[] subSeqMutations;
                        Mutations<NucleotideSequence> mmutations;
                        synchronized (mutationModel) {
                            mmutations = generateMutations(subSeq, mutationModel);
                            subSeqMutations = mmutations.getAllMutations();
                        }
                        float actionScore = AlignmentUtils.calculateScore(parameters.getScoring(),
                                subSeq.size(), mmutations);

                        int indels = 0;
                        for (int mut : subSeqMutations)
                            if (isDeletion(mut) || isInsertion(mut))
                                ++indels;

                        NucleotideSequence target = left.concatenate(mutate(subSeq, subSeqMutations))
                                .concatenate(right);

                        timestamp = System.nanoTime();
                        KAlignmentResult result = aligner.align(target);
                        time.addAndGet(System.nanoTime() - timestamp);

                        boolean found = false;
                        for (KAlignmentHit hit : result.hits) {
                            if (hit.getId() == id) {
                                //System.out.println(hit.getAlignmentScore());
                                found = true;
                                if (!parameters.isFloatingLeftBound())
                                    Assert.assertTrue(hit.getAlignment().getSequence1Range().getFrom() == 0
                                            || hit.getAlignment().getSequence2Range().getFrom() == 0);
                                if (!parameters.isFloatingRightBound())
                                    Assert.assertTrue(hit.getAlignment().getSequence1Range().getTo() == ref
                                            .size()
                                            || hit.getAlignment().getSequence2Range().getTo() == target.size());
                                if (hit.getAlignment().getScore() < actionScore
                                        && indels <= parameters.getMaxAdjacentIndels()) {
                                    scoreError.incrementAndGet();
                                    //System.out.println(target);
                                    //System.out.println(left);
                                    //printAlignment(subSeq, subSeqMutations);
                                    //System.out.println(right);
                                    //printHitAlignment(hit);
                                    ////printAlignment(ncs.get(hit.getId()).getRange(hit.getAlignment().getSequence1Range()),
                                    ////        hit.getAlignment().getMutations());
                                    //found = true;
                                }
                            } else {
                                //printHitAlignment(hit);
                                //System.out.println(hit.getAlignmentScore());
                                incorrect.incrementAndGet();
                            }
                        }

                        if (found)
                            correct.incrementAndGet();
                        else {
                            if (indels <= parameters.getMaxAdjacentIndels()) {
                                miss.incrementAndGet();
                                //System.out.println(target);
                                //System.out.println(left);
                                //printAlignment(subSeq, subSeqMutations);
                                //System.out.println(right);
                            }
                        }

                        NucleotideSequence randomSequence = randomSequence(NucleotideSequence.ALPHABET, rdi,
                                target.size() - 1, target.size());
                        for (KAlignmentHit hit : aligner.align(randomSequence).hits) {
                            hit.calculateAlignmnet();
                            if (hit.getAlignment().getScore() >= 110.0)
                                random.incrementAndGet();
                        }
                    }
                }
            };
        }

        for (i = 0; i < threadCount; ++i)
            threads[i].start();

        for (i = 0; i < threadCount; ++i)
            threads[i].join();

        System.out.println("C=" + correct.get() + ";I=" + incorrect.get() + ";M=" + miss.get() + ";ScE="
                + scoreError.get() + ";R=" + (1.0 * random.get() / baseSize / total) + " AlignmentTime = "
                + time(time.get() / total));
        Assert.assertEquals(1.0, 1.0 * correct.get() / total, 0.01);
        Assert.assertEquals(0.0, 1.0 * incorrect.get() / total, 0.001);
        Assert.assertEquals(0.0, 1.0 * miss.get() / total, 0.001);
        Assert.assertEquals(0.0, 1.0 * scoreError.get() / total, 0.001);
        Assert.assertEquals(0.0, 1.0 * random.get() / total / baseSize, 5E-6);
    }
}

From source file:edu.cmu.graphchi.engine.HypergraphChiEngine.java

private void loadBeforeUpdates(int interval, final ChiVertex<VertexDataType, EdgeDataType>[] vertices,
        final MemoryShard<EdgeDataType> memShard, final int startVertex, final int endVertex)
        throws IOException {
    final Object terminationLock = new Object();
    final TimerContext _timer = loadTimer.time();
    // TODO: make easier to read
    synchronized (terminationLock) {

        final AtomicInteger countDown = new AtomicInteger(disableOutEdges ? 1 : nShards);

        if (!disableInEdges) {
            try {

                logger.info("Memshard: " + startVertex + " -- " + endVertex);
                memShard.loadVertices(startVertex, endVertex, vertices, disableOutEdges, parallelExecutor);
                logger.info("Loading memory-shard finished." + Thread.currentThread().getName());

                if (countDown.decrementAndGet() == 0) {
                    synchronized (terminationLock) {
                        terminationLock.notifyAll();
                    }// w  w  w . j  a  va2  s.c  o  m
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                throw new RuntimeException(ioe);
            } catch (Exception err) {
                err.printStackTrace();
            }
        }

        /* Load in parallel */
        if (!disableOutEdges) {
            for (int p = 0; p < nShards; p++) {
                if (p != interval || disableInEdges) {
                    final int _p = p;
                    final SlidingShard<EdgeDataType> shard = slidingShards.get(p);
                    loadingExecutor.submit(new Runnable() {

                        public void run() {
                            try {
                                shard.readNextVertices(vertices, startVertex, false);
                                if (countDown.decrementAndGet() == 0) {
                                    synchronized (terminationLock) {
                                        terminationLock.notifyAll();
                                    }
                                }

                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                                throw new RuntimeException(ioe);
                            } catch (Exception err) {
                                err.printStackTrace();
                            }
                        }
                    });
                }
            }
        }

        // barrier
        try {
            while (countDown.get() > 0) {
                terminationLock.wait(5000);
                if (countDown.get() > 0) {
                    logger.info("Still waiting for loading, counter is: " + countDown.get());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    _timer.stop();
}

From source file:org.rhq.server.metrics.MetricsServer.java

public void addNumericData(final Set<MeasurementDataNumeric> dataSet, final RawDataInsertedCallback callback) {
    if (log.isDebugEnabled()) {
        log.debug("Inserting " + dataSet.size() + " raw metrics");
    }/*from w  w  w  .ja va2 s. c o m*/
    final Stopwatch stopwatch = new Stopwatch().start();
    final AtomicInteger remainingInserts = new AtomicInteger(dataSet.size());
    // TODO add support for splitting cache index partition
    final int partition = 0;

    for (final MeasurementDataNumeric data : dataSet) {
        DateTime collectionTimeSlice = dateTimeService.getTimeSlice(new DateTime(data.getTimestamp()),
                configuration.getRawTimeSliceDuration());
        Days days = Days.daysBetween(collectionTimeSlice, dateTimeService.now());

        if (days.isGreaterThan(rawDataAgeLimit)) {
            callback.onSuccess(data);
            continue;
        }

        StorageResultSetFuture rawFuture = dao.insertRawData(data);
        StorageResultSetFuture indexFuture = dao.updateIndex(IndexBucket.RAW, collectionTimeSlice.getMillis(),
                data.getScheduleId());
        ListenableFuture<List<ResultSet>> insertsFuture = Futures.successfulAsList(rawFuture, indexFuture);
        Futures.addCallback(insertsFuture, new FutureCallback<List<ResultSet>>() {
            @Override
            public void onSuccess(List<ResultSet> result) {
                callback.onSuccess(data);
                if (remainingInserts.decrementAndGet() == 0) {
                    stopwatch.stop();
                    if (log.isDebugEnabled()) {
                        log.debug("Finished inserting " + dataSet.size() + " raw metrics in "
                                + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
                    }
                    callback.onFinish();
                }
            }

            @Override
            public void onFailure(Throwable t) {
                if (log.isDebugEnabled()) {
                    log.debug("An error occurred while inserting raw data", ThrowableUtil.getRootCause(t));
                } else {
                    log.warn("An error occurred while inserting raw data: " + ThrowableUtil.getRootMessage(t));
                }
                callback.onFailure(t);
            }
        }, tasks);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestDelegationTokenRenewer.java

private DelegationTokenRenewer createNewDelegationTokenRenewer(Configuration conf,
        final AtomicInteger counter) {
    DelegationTokenRenewer renew = new DelegationTokenRenewer() {

        @Override/*  ww w  .  j a  v  a 2 s.  co m*/
        protected ThreadPoolExecutor createNewThreadPoolService(Configuration conf) {
            ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 3L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>()) {

                @Override
                protected void afterExecute(Runnable r, Throwable t) {
                    counter.decrementAndGet();
                    super.afterExecute(r, t);
                }

                @Override
                public void execute(Runnable command) {
                    counter.incrementAndGet();
                    super.execute(command);
                }
            };
            return pool;
        }
    };
    renew.setRMContext(TestUtils.getMockRMContext());
    return renew;
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testMultiClient() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
    final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger max = new AtomicInteger(0);
    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < QTY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override/*from   w  ww .j  a  v  a2s.c  o  m*/
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        timing.session(), timing.connection(), new RetryOneTime(1));
                try {
                    client.start();
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));
                } finally {
                    IOUtils.closeQuietly(client);
                }

                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> f : futures) {
        f.get();
    }
    Assert.assertEquals(count.get(), 0);
    Assert.assertEquals(max.get(), QTY);
}

From source file:org.b3log.latke.ioc.JavassistMethodHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Method proceed, final Object[] params)
        throws Throwable {
    LOGGER.trace("Processing invocation [" + method.toString() + "]");

    AtomicInteger calls = CALLS.get();
    if (null == calls) {
        synchronized (this) {
            if (null == calls) {
                calls = new AtomicInteger(0);
                CALLS.set(calls);/*from   www .j  a v a  2s  . c  o  m*/
            }
        }
    }
    calls.incrementAndGet();

    // Invocation with transaction handle
    final boolean withTransactionalAnno = method.isAnnotationPresent(Transactional.class);
    JdbcTransaction transaction = JdbcRepository.TX.get();
    final boolean alreadyInTransaction = null != transaction;
    final boolean needHandleTrans = withTransactionalAnno && !alreadyInTransaction;

    // Transaction Propagation: REQUIRED (Support a current transaction, create a new one if none exists)
    if (needHandleTrans) {
        try {
            transaction = new JdbcTransaction();
        } catch (final SQLException e) {
            LOGGER.log(Level.ERROR, "Failed to initialize JDBC transaction", e);

            throw new IllegalStateException("Begin a transaction failed");
        }

        JdbcRepository.TX.set(transaction);
    }

    Object ret;
    try {
        ret = proceed.invoke(proxy, params);

        if (needHandleTrans) {
            transaction.commit();
        }
    } catch (final InvocationTargetException e) {
        if (needHandleTrans) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }

        throw e.getTargetException();
    }

    if (0 == calls.decrementAndGet()) {
        CALLS.set(null);
        final Connection connection = JdbcRepository.CONN.get();
        if (null != connection) {
            connection.close();
            JdbcRepository.CONN.set(null);
        }
    }

    return ret;
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphore.java

@Test
public void testRelease1AtATime() throws Exception {
    final int CLIENT_QTY = 10;
    final int MAX = CLIENT_QTY / 2;
    final AtomicInteger maxLeases = new AtomicInteger(0);
    final AtomicInteger activeQty = new AtomicInteger(0);
    final AtomicInteger uses = new AtomicInteger(0);

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        Future<Object> f = service.submit(new Callable<Object>() {
            @Override/*from w ww.java 2  s.c o m*/
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX);
                    Lease lease = semaphore.acquire(10, TimeUnit.SECONDS);
                    Assert.assertNotNull(lease);
                    uses.incrementAndGet();
                    try {
                        synchronized (maxLeases) {
                            int qty = activeQty.incrementAndGet();
                            if (qty > maxLeases.get()) {
                                maxLeases.set(qty);
                            }
                        }

                        Thread.sleep(500);
                    } finally {
                        activeQty.decrementAndGet();
                        lease.close();
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        });
        futures.add(f);
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    Assert.assertEquals(uses.get(), CLIENT_QTY);
    Assert.assertEquals(maxLeases.get(), MAX);
}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {// w w w.ja  v a  2s. c om
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}