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

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

Introduction

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

Prototype

public final int incrementAndGet() 

Source Link

Document

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

Usage

From source file:de.pixida.logtest.designer.automaton.EditorAutomaton.java

private void assignArbitraryIdsToNodesAndEdges() {
    final AtomicInteger idCounter = new AtomicInteger();
    this.graph.getAllNodesByClass(AutomatonNode.class)
            .forEach(node -> node.setId(String.valueOf(idCounter.incrementAndGet())));
    this.graph.getAllNodesByClass(AutomatonEdge.class)
            .forEach(edge -> edge.setId(String.valueOf(idCounter.incrementAndGet())));
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatch.java

private void retryRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.retryingRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(RETRY_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }//from  w  w  w  .j  a va  2s . c  o  m
    inboundRequest.setAttribute(RETRY_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxRetryAttempts) {
        if (retrySleep > 0) {
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.retrySleepFailed(resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxRetryAttemptsReached(maxRetryAttempts, resourceRole, outboundRequest.getURI().toString());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluatedWithAutoCommit()
        throws Exception {
    // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but
    // then iterated in another.  note that Gremlin Server configures the script engine to auto-commit
    // after evaluation.  this basically tests the state of the Gremlin Server GremlinExecutor when
    // being used in sessionless mode
    final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterSuccess(b -> {
        final GraphTraversalSource g = (GraphTraversalSource) b.get("g");
        if (g.getGraph().features().graph().supportsTransactions())
            g.tx().commit();/*from ww w.j ava2 s  . co  m*/
    }).executorService(evalExecutor).create();

    final Map<String, Object> bindings = new HashMap<>();
    bindings.put("g", g);

    final AtomicInteger vertexCount = new AtomicInteger(0);

    final ExecutorService iterationExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    gremlinExecutor.eval("g.V().out()", bindings).thenAcceptAsync(o -> {
        final Iterator itty = (Iterator) o;
        itty.forEachRemaining(v -> vertexCount.incrementAndGet());
    }, iterationExecutor).join();

    assertEquals(6, vertexCount.get());

    gremlinExecutor.close();
    evalExecutor.shutdown();
    evalExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
    iterationExecutor.shutdown();
    iterationExecutor.awaitTermination(30000, TimeUnit.MILLISECONDS);
}

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

@Test
public void testCompressionProvider() throws Exception {
    final byte[] data = "here's a string".getBytes();

    final AtomicInteger compressCounter = new AtomicInteger();
    final AtomicInteger decompressCounter = new AtomicInteger();
    CompressionProvider compressionProvider = new CompressionProvider() {
        @Override/*ww w .j av a  2s.  co m*/
        public byte[] compress(String path, byte[] data) throws Exception {
            compressCounter.incrementAndGet();

            byte[] bytes = new byte[data.length * 2];
            System.arraycopy(data, 0, bytes, 0, data.length);
            System.arraycopy(data, 0, bytes, data.length, data.length);
            return bytes;
        }

        @Override
        public byte[] decompress(String path, byte[] compressedData) throws Exception {
            decompressCounter.incrementAndGet();

            byte[] bytes = new byte[compressedData.length / 2];
            System.arraycopy(compressedData, 0, bytes, 0, bytes.length);
            return bytes;
        }
    };

    CuratorFramework client = CuratorFrameworkFactory.builder().compressionProvider(compressionProvider)
            .connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try {
        client.start();

        client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c", data);

        Assert.assertNotEquals(data, client.getData().forPath("/a/b/c"));
        Assert.assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length);
    } finally {
        IOUtils.closeQuietly(client);
    }

    Assert.assertEquals(compressCounter.get(), 1);
    Assert.assertEquals(decompressCounter.get(), 1);
}

From source file:io.pravega.client.state.impl.SynchronizerTest.java

@Test(timeout = 20000)
public void testCompaction() throws EndOfSegmentException {
    String streamName = "streamName";
    String scope = "scope";

    MockSegmentStreamFactory ioFactory = new MockSegmentStreamFactory();
    @Cleanup/*  w ww .  j a  va 2s.  c  o m*/
    MockClientFactory clientFactory = new MockClientFactory(scope, ioFactory);
    StateSynchronizer<RevisionedImpl> sync = clientFactory.createStateSynchronizer(streamName,
            new JavaSerializer<>(), new JavaSerializer<>(), SynchronizerConfig.builder().build());
    AtomicInteger callCount = new AtomicInteger(0);
    sync.initialize(new RegularUpdate());
    sync.updateState(state -> {
        callCount.incrementAndGet();
        return Collections.singletonList(new RegularUpdate());
    });
    assertEquals(1, callCount.get());
    sync.updateState(state -> {
        callCount.incrementAndGet();
        return Collections.singletonList(new RegularUpdate());
    });
    assertEquals(2, callCount.get());
    sync.compact(state -> {
        callCount.incrementAndGet();
        return new RegularUpdate();
    });
    assertEquals(3, callCount.get());
    sync.updateState(s -> {
        callCount.incrementAndGet();
        return Collections.singletonList(new RegularUpdate());
    });
    assertEquals(5, callCount.get());
    sync.compact(state -> {
        callCount.incrementAndGet();
        return new RegularUpdate();
    });
    assertEquals(6, callCount.get());
}

From source file:de.tudarmstadt.ukp.dkpro.core.norvig.NorvigSpellingAlgorithm.java

/**
 * Read words from the given reader and count their occurrences.
 *
 * @param aReader//from  w w w  . j  a  v  a 2  s  .co m
 *            the reader.
 * @throws IOException
 *             if the words cannot be read.
 */
public void train(Reader aReader) throws IOException {
    BufferedReader in = new BufferedReader(aReader);

    String line = in.readLine();
    while (line != null) {
        Matcher m = WORD_PATTERN.matcher(line.toLowerCase());

        while (m.find()) {
            String word = m.group();
            AtomicInteger count = nWords.get(word);
            if (count == null) {
                count = new AtomicInteger(0);
                nWords.put(word, count);
            }
            count.incrementAndGet();
        }

        line = in.readLine();
    }
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch.java

private void retryRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.retryingRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(RETRY_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }/*w  w w  .  j av a2  s .c  o  m*/
    inboundRequest.setAttribute(RETRY_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxRetryAttempts) {
        if (retrySleep > 0) {
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.retrySleepFailed(RESOURCE_ROLE, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxRetryAttemptsReached(maxRetryAttempts, RESOURCE_ROLE, outboundRequest.getURI().toString());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:fr.landel.utils.assertor.utils.AssertorMap.java

private static <M extends Map<K, V>, K, V, T> boolean hasInOrder(final M map, final Iterable<T> objects,
        final boolean not, final EnumAnalysisMode analysisMode,
        final BiPredicate<Entry<K, V>, T> entriesEqualChecker, final Class<T> objectsClass) {

    int found = 0;

    final int size1 = map.size();
    final int size2 = IterableUtils.size(objects);

    if (size1 < size2) {
        return not;
    }//from w w w .ja  v  a 2 s  .com

    final Set<Entry<K, V>> entries1 = map.entrySet();
    final List<T> entries2 = IterableUtils.toList(objects);

    if (EnumAnalysisMode.STANDARD.equals(analysisMode)) {
        for (Entry<K, V> entry1 : entries1) {
            if (found < size2) {
                if (entriesEqualChecker.test(entry1, entries2.get(found))) {
                    ++found;
                } else if (found > 0) {
                    found = 0;
                }
            }
        }
    } else {
        final AtomicInteger count = new AtomicInteger(0);

        final Stream<Entry<K, V>> stream;
        if (EnumAnalysisMode.PARALLEL.equals(analysisMode)) {
            stream = entries1.parallelStream();
        } else {
            stream = entries1.stream();
        }

        stream.forEachOrdered(o -> {
            int inc = count.get();
            if (inc < size2) {
                if (entriesEqualChecker.test(o, entries2.get(inc))) {
                    count.incrementAndGet();
                } else if (inc > 0) {
                    count.set(0);
                }
            }
        });

        found = count.get();
    }

    return not ^ (found == size2);
}

From source file:fi.luontola.cqrshotel.framework.EventStoreContract.java

@Test
public void concurrent_writers_to_different_streams() throws Exception {
    final int BATCH_SIZE = 10;
    final int ITERATIONS = 100;

    long initialPosition = eventStore.getCurrentPosition();
    AtomicInteger taskIdSeq = new AtomicInteger(0);

    repeatInParallel(ITERATIONS, () -> {
        UUID streamId = UUID.randomUUID();
        int taskId = taskIdSeq.incrementAndGet();
        List<Event> batch = createBatch(BATCH_SIZE, taskId);

        eventStore.saveEvents(streamId, batch, EventStore.BEGINNING);
    }, createRuntimeInvariantChecker(BATCH_SIZE));

    List<Event> allEvents = eventStore.getAllEvents(initialPosition);
    assertThat("number of saved events", allEvents.size(), is(BATCH_SIZE * ITERATIONS));
    assertAtomicBatches(BATCH_SIZE, allEvents);
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatch.java

private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.failingOverRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }/*from  w ww.  j  av a  2  s .co  m*/
    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxFailoverAttempts) {
        haProvider.markFailedURL(resourceRole, outboundRequest.getURI().toString());
        //null out target url so that rewriters run again
        inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);
        URI uri = getDispatchUrl(inboundRequest);
        ((HttpRequestBase) outboundRequest).setURI(uri);
        if (failoverSleep > 0) {
            try {
                Thread.sleep(failoverSleep);
            } catch (InterruptedException e) {
                LOG.failoverSleepFailed(resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxFailoverAttemptsReached(maxFailoverAttempts, resourceRole);
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}