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

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

Introduction

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

Prototype

public final void set(int newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:com.unboundid.scim.marshal.json.JsonUnmarshaller.java

/**
 * {@inheritDoc}/* w w w .  j  ava 2 s  .  c  o m*/
 */
public void bulkUnmarshal(final File file, final BulkConfig bulkConfig, final BulkContentHandler handler)
        throws SCIMException {
    // First pass: ensure the number of operations is less than the max,
    // and save the failOnErrrors value.
    final AtomicInteger failOnErrorsValue = new AtomicInteger(-1);
    final BulkContentHandler preProcessHandler = new BulkContentHandler() {
        @Override
        public void handleFailOnErrors(final int failOnErrors) {
            failOnErrorsValue.set(failOnErrors);
        }
    };
    try {
        final FileInputStream fileInputStream = new FileInputStream(file);
        try {
            final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            try {
                final JsonBulkParser jsonBulkParser = new JsonBulkParser(bufferedInputStream, bulkConfig,
                        preProcessHandler);
                jsonBulkParser.setSkipOperations(true);
                jsonBulkParser.unmarshal();
            } finally {
                bufferedInputStream.close();
            }
        } finally {
            fileInputStream.close();
        }
    } catch (IOException e) {
        Debug.debugException(e);
        throw new ServerErrorException("Error pre-processing bulk request: " + e.getMessage());
    }

    int failOnErrors = failOnErrorsValue.get();
    if (failOnErrors != -1) {
        handler.handleFailOnErrors(failOnErrors);
    }

    // Second pass: Parse fully.
    try {
        final FileInputStream fileInputStream = new FileInputStream(file);
        try {
            final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            try {
                final JsonBulkParser jsonBulkParser = new JsonBulkParser(bufferedInputStream, bulkConfig,
                        handler);
                jsonBulkParser.unmarshal();
            } finally {
                bufferedInputStream.close();
            }
        } finally {
            fileInputStream.close();
        }
    } catch (IOException e) {
        Debug.debugException(e);
        throw new ServerErrorException("Error parsing bulk request: " + e.getMessage());
    }
}

From source file:org.apache.camel.processor.LoopProcessor.java

@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    // use atomic integer to be able to pass reference and keep track on the values
    AtomicInteger index = new AtomicInteger();
    AtomicInteger count = new AtomicInteger();

    // Intermediate conversion to String is needed when direct conversion to Integer is not available
    // but evaluation result is a textual representation of a numeric value.
    String text = expression.evaluate(exchange, String.class);
    try {//w w w  . j a  v a 2s  .c  om
        int num = ExchangeHelper.convertToMandatoryType(exchange, Integer.class, text);
        count.set(num);
    } catch (NoTypeConversionAvailableException e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }

    // set the size before we start
    exchange.setProperty(Exchange.LOOP_SIZE, count);

    // loop synchronously
    while (index.get() < count.get()) {

        // and prepare for next iteration
        ExchangeHelper.prepareOutToIn(exchange);
        boolean sync = process(exchange, callback, index, count);

        if (!sync) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                        + " is continued being processed asynchronously");
            }
            // the remainder of the routing slip will be completed async
            // so we break out now, then the callback will be invoked which then continue routing from where we left here
            return false;
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchangeId: " + exchange.getExchangeId()
                    + " is continued being processed synchronously");
        }

        // increment counter before next loop
        index.getAndIncrement();
    }

    // we are done so prepare the result
    ExchangeHelper.prepareOutToIn(exchange);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Processing complete for exchangeId: " + exchange.getExchangeId() + " >>> " + exchange);
    }
    callback.done(true);
    return true;
}

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

private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, AtomicInteger maxConcurrentCount,
        Random random, int maxAllowed) throws Exception {
    try {/*  ww w.j  a v  a 2  s  . c  om*/
        Assert.assertTrue(lock.acquire(10, TimeUnit.SECONDS));
        int localConcurrentCount;
        synchronized (this) {
            localConcurrentCount = concurrentCount.incrementAndGet();
            if (localConcurrentCount > maxConcurrentCount.get()) {
                maxConcurrentCount.set(localConcurrentCount);
            }
        }

        Assert.assertTrue(localConcurrentCount <= maxAllowed, "" + localConcurrentCount);

        Thread.sleep(random.nextInt(9) + 1);
    } finally {
        synchronized (this) {
            concurrentCount.decrementAndGet();
            lock.release();
        }
    }
}

From source file:org.chromium.android_webview.test.AwContentsTest.java

private int callDocumentHasImagesSync(final AwContents awContents) throws Throwable, InterruptedException {
    // Set up a container to hold the result object and a semaphore to
    // make the test wait for the result.
    final AtomicInteger val = new AtomicInteger();
    final Semaphore s = new Semaphore(0);
    final Message msg = Message.obtain(new Handler(Looper.getMainLooper()) {
        @Override//  w w  w  . j  a  v a  2  s. c  om
        public void handleMessage(Message msg) {
            val.set(msg.arg1);
            s.release();
        }
    });
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            awContents.documentHasImages(msg);
        }
    });
    assertTrue(s.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    int result = val.get();
    return result;
}

From source file:org.apache.tinkerpop.gremlin.driver.ResultQueueTest.java

@Test
public void shouldDrainAsItemsArrive() throws Exception {
    final Thread t = addToQueue(1000, 1, true);
    try {/*  www  . j  a  v a  2 s .c  o m*/
        final AtomicInteger count1 = new AtomicInteger(0);
        final AtomicInteger count2 = new AtomicInteger(0);
        final AtomicInteger count3 = new AtomicInteger(0);
        final CountDownLatch latch = new CountDownLatch(3);

        resultQueue.await(500).thenAcceptAsync(r -> {
            count1.set(r.size());
            latch.countDown();
        });

        resultQueue.await(150).thenAcceptAsync(r -> {
            count2.set(r.size());
            latch.countDown();
        });

        resultQueue.await(350).thenAcceptAsync(r -> {
            count3.set(r.size());
            latch.countDown();
        });

        assertThat(latch.await(3000, TimeUnit.MILLISECONDS), is(true));

        assertEquals(500, count1.get());
        assertEquals(150, count2.get());
        assertEquals(350, count3.get());

        assertThat(resultQueue.isEmpty(), is(true));
    } finally {
        t.interrupt();
    }
}

From source file:org.bpmscript.process.memory.MemoryBpmScriptManager.java

/**
 * Call the callback with the instance reference by the pid. Should be used in
 * conjunction with a locking mechanism, e.g. LockingInstanceManager
 * /*from   w  ww.  java 2  s  . c  om*/
 * @see LockingInstanceManager
 */
public IExecutorResult doWithInstance(String processInstanceId, IInstanceCallback callback) throws Exception {
    AtomicInteger lock = null;
    synchronized (locks) {
        lock = locks.get(processInstanceId);
        if (lock == null) {
            lock = new AtomicInteger(1);
            locks.put(processInstanceId, lock);
        } else {
            lock.set(lock.get() + 1);
        }
    }
    IExecutorResult result = null;
    synchronized (lock) {
        try {
            log.debug("locking " + processInstanceId + " " + lock);
            MemoryInstance processInstance = memoryInstances.get(processInstanceId);
            result = callback.execute(processInstance);
            if (result.getProcessState() != ProcessState.IGNORED) {
                processInstance.setLastModified(new Timestamp(System.currentTimeMillis()));
            }
        } finally {
            log.debug("unlocking " + processInstanceId);
            lock.set(lock.get() - 1);
            if (lock.get() == 0) {
                locks.remove(processInstanceId);
            }
        }
    }
    return result;

}

From source file:org.kawanfw.sql.jdbc.BlobHttp.java

/**
 * Constructor used when reading a downloaded Blob
 * /*  ww w  .  java2s  .c  om*/
 * @param in
 *            the input stream of the Blob whic maps a
 *            {@code remoteInputStream}
 * @param connection
 *            the Connection to the remote servers which maps a
 *            {@code ConnectionHttp}
 */
BlobHttp(InputStream in, Connection connection) throws SQLException {

    this();

    OutputStream out = null;

    try {

        if (in == null) {
            throw new IllegalArgumentException(Tag.PRODUCT_PRODUCT_FAIL + " i is null.");
        }

        if (connection == null) {
            throw new IllegalArgumentException(Tag.PRODUCT_PRODUCT_FAIL + " connection is null.");
        }

        if (!(in instanceof RemoteInputStream)) {
            throw new IllegalArgumentException(
                    Tag.PRODUCT_PRODUCT_FAIL + " in is not instance of RemoteInputStream.");
        }

        if (!(connection instanceof ConnectionHttp)) {
            throw new IllegalArgumentException(
                    Tag.PRODUCT_PRODUCT_FAIL + " in is not instance of RemoteConnection.");
        }

        AtomicInteger progress = ((ConnectionHttp) connection).getProgress();
        AtomicBoolean cancelled = ((ConnectionHttp) connection).getCancelled();

        // reinit progress
        progress.set(0);

        long totalLength = ((RemoteInputStream) in).length();

        out = new BufferedOutputStream(new FileOutputStream(file));

        int tempLen = 0;
        byte[] buffer = new byte[1024 * 4];
        int n = 0;

        while ((n = in.read(buffer)) != -1) {
            tempLen += n;

            if (totalLength > 0 && tempLen > totalLength / 100) {
                tempLen = 0;
                int cpt = progress.get();
                cpt++;

                // Update the progress value for progress
                // indicator
                progress.set(Math.min(99, cpt));
            }

            // If progress indicator says that user has cancelled the
            // download, stop now!
            if (cancelled.get()) {
                throw new InterruptedException("Blob download cancelled by user.");
            }

            out.write(buffer, 0, n);
        }

    } catch (Exception e) {
        JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}

From source file:org.apache.hadoop.hive.ql.exec.tez.TestHostAffinitySplitLocationProvider.java

private double testHashDistribution(int locs, final int missCount, FileSplit[] splits,
        AtomicInteger errorCount) {
    // This relies heavily on what method determineSplits ... calls and doesn't.
    // We could do a wrapper with only size() and get() methods instead of List, to be sure.
    @SuppressWarnings("unchecked")
    List<String> partLocs = (List<String>) Mockito.mock(List.class);
    Mockito.when(partLocs.size()).thenReturn(locs);
    final AtomicInteger state = new AtomicInteger(0);
    Mockito.when(partLocs.get(Mockito.anyInt())).thenAnswer(new Answer<String>() {
        @Override/* w  w w .  j a v a2s. c  om*/
        public String answer(InvocationOnMock invocation) throws Throwable {
            return (state.getAndIncrement() == missCount) ? "not-null" : null;
        }
    });
    int[] hitCounts = new int[locs];
    for (int splitIx = 0; splitIx < splits.length; ++splitIx) {
        state.set(0);
        int index = HostAffinitySplitLocationProvider.determineLocation(partLocs,
                splits[splitIx].getPath().toString(), splits[splitIx].getStart(), null);
        ++hitCounts[index];
    }
    SummaryStatistics ss = new SummaryStatistics();
    for (int hitCount : hitCounts) {
        ss.addValue(hitCount);
    }
    // All of this is completely bogus and mostly captures the following function:
    // f(output) = I-eyeballed-the(output) == they-look-ok.
    // It's pretty much a golden file... 
    // The fact that stdev doesn't increase with increasing missCount is captured outside.
    double avg = ss.getSum() / ss.getN(), stdev = ss.getStandardDeviation(), cv = stdev / avg;
    double allowedMin = avg - 2.5 * stdev, allowedMax = avg + 2.5 * stdev;
    if (allowedMin > ss.getMin() || allowedMax < ss.getMax() || cv > 0.22) {
        LOG.info("The distribution for " + locs + " locations, " + missCount + " misses isn't to "
                + "our liking: avg " + avg + ", stdev " + stdev + ", cv " + cv + ", min " + ss.getMin()
                + ", max " + ss.getMax());
        errorCount.incrementAndGet();
    }
    return cv;
}

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

@Test
public void testCheckAndDelete() throws InterruptedException, ExecutionException {
    AsyncTableBase table = getTable.get();
    int count = 10;
    CountDownLatch putLatch = new CountDownLatch(count + 1);
    table.put(new Put(row).addColumn(FAMILY, QUALIFIER, VALUE)).thenRun(() -> putLatch.countDown());
    IntStream.range(0, count)/* w w w.  j av  a  2  s. co m*/
            .forEach(i -> table.put(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), VALUE))
                    .thenRun(() -> putLatch.countDown()));
    putLatch.await();

    AtomicInteger successCount = new AtomicInteger(0);
    AtomicInteger successIndex = new AtomicInteger(-1);
    CountDownLatch deleteLatch = new CountDownLatch(count);
    IntStream.range(0, count).forEach(i -> table
            .checkAndDelete(row, FAMILY, QUALIFIER, VALUE,
                    new Delete(row).addColumn(FAMILY, QUALIFIER).addColumn(FAMILY, concat(QUALIFIER, i)))
            .thenAccept(x -> {
                if (x) {
                    successCount.incrementAndGet();
                    successIndex.set(i);
                }
                deleteLatch.countDown();
            }));
    deleteLatch.await();
    assertEquals(1, successCount.get());
    Result result = table.get(new Get(row)).get();
    IntStream.range(0, count).forEach(i -> {
        if (i == successIndex.get()) {
            assertFalse(result.containsColumn(FAMILY, concat(QUALIFIER, i)));
        } else {
            assertArrayEquals(VALUE, result.getValue(FAMILY, concat(QUALIFIER, i)));
        }
    });
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldOverrideBeforeEval() throws Exception {
    final AtomicInteger called = new AtomicInteger(0);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().beforeEval(b -> called.set(1)).create();
    assertEquals(2, gremlinExecutor.eval("1+1", null, new SimpleBindings(),
            GremlinExecutor.LifeCycle.build().beforeEval(b -> called.set(200)).create()).get());

    // need to wait long enough for the callback to register
    Thread.sleep(500);//  w w  w. ja v a 2  s.c om

    assertEquals(200, called.get());
}