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:org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatch.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);
    }//  w w w . ja  v  a2 s  .  c o  m
    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxFailoverAttempts) {
        haProvider.markFailedURL(getServiceRole(), 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(getServiceRole(), e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxFailoverAttemptsReached(maxFailoverAttempts, getServiceRole());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:dk.statsbiblioteket.util.JobControllerTest.java

public void testEmptyPop() throws Exception {
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10) {
        @Override/*from  w ww .  j av a2s.  c o m*/
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    assertTrue("Popping on empty should return empty list",
            controller.popAll(10, TimeUnit.MILLISECONDS).isEmpty());
    assertEquals("The callback count should zero on empty controller", 0, counter.get());
}

From source file:org.jtheque.undo.UndoServiceTest.java

@Test
@DirtiesContext/*w w  w  .  j  a  va 2s  .  co  m*/
public void listenerCalled() {
    final AtomicInteger counter = new AtomicInteger(0);

    undoService.addStateListener(new StateListener() {
        @Override
        public void stateChanged(String undoName, boolean canUndo, String redoName, boolean canRedo) {
            counter.incrementAndGet();
        }
    });

    undoService.addEdit(new TestEdit(new AtomicInteger(0), new AtomicInteger(0)));

    assertEquals(1, counter.intValue());

    undoService.addEdit(new TestEdit(new AtomicInteger(0), new AtomicInteger(0)));

    assertEquals(2, counter.intValue());

    undoService.undo();

    assertEquals(3, counter.intValue());

    undoService.redo();

    assertEquals(4, counter.intValue());
}

From source file:com.norconex.committer.AbstractFileQueueCommitterTest.java

@Test
public void testMultipleCommitThread() throws Exception {

    final AtomicInteger counter = new AtomicInteger();

    final AbstractFileQueueCommitter committer = new AbstractFileQueueCommitter() {

        @Override/*from w w  w.  j a  va 2 s.  co m*/
        protected void commitAddition(IAddOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitDeletion(IDeleteOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitComplete() {
        }
    };

    File queue = temp.newFolder();
    committer.setQueueDir(queue.getPath());
    // Use a bigger number to make sure the files are not 
    // committed while they are added.
    committer.setQueueSize(1000);

    // Queue 50 files for additions
    for (int i = 0; i < 50; i++) {
        Properties metadata = new Properties();
        committer.add(Integer.toString(i), IOUtils.toInputStream("hello world!"), metadata);
    }
    // Queue 50 files for deletions
    for (int i = 50; i < 100; i++) {
        Properties metadata = new Properties();
        committer.remove(Integer.toString(i), metadata);
    }

    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    committer.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);

    // Each file should have been processed exactly once
    assertEquals(100, counter.intValue());

    // All files should have been processed
    Collection<File> files = FileUtils.listFiles(queue, null, true);
    assertTrue(files.isEmpty());
}

From source file:dk.statsbiblioteket.util.JobControllerTest.java

public void testRemoveCallback() throws Exception {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10) {
        @Override/*from   ww w.  jav  a 2  s .  com*/
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        controller.submit(new Shout(10));
    }
    synchronized (Thread.currentThread()) {
        Thread.currentThread().wait(100);
    }
    assertEquals("The number of pops should match", JOBS, controller.popAll().size());
    assertEquals("The number of callbacks should match", JOBS, counter.get());
}

From source file:org.apache.hadoop.hdfs.TestDfsClientCreateParentCompatibility.java

@Test
public void testCreateWithoutDirsCompatibility() throws IOException {
    Configuration conf = new Configuration();
    NameNode nn = mock(NameNode.class);

    final String err = "java.io.IOException: " + "java.lang.NoSuchMethodException: org.apache.hadoop.hdfs."
            + "protocol.ClientProtocol.create(java.lang.String, "
            + "org.apache.hadoop.fs.permission.FsPermission, "
            + "java.lang.String, boolean, boolean, short, long)";
    final AtomicInteger newCount = new AtomicInteger();
    Answer<Void> newCallCounter = new Answer<Void>() {
        @Override/*from   www .  j av a 2 s.com*/
        public Void answer(InvocationOnMock invocation) throws Throwable {
            LOG.info("New Call " + Arrays.toString(invocation.getArguments()));
            newCount.incrementAndGet();
            throw new RemoteException(IOException.class.getName(), err);
        }
    };

    final AtomicInteger oldCount = new AtomicInteger();
    Answer<Void> oldCallCounter = new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            LOG.info("Old Call " + Arrays.toString(invocation.getArguments()));
            oldCount.incrementAndGet();
            return null;
        }
    };

    // new api client call
    doAnswer(newCallCounter).when(nn).create((String) anyObject(), (FsPermission) anyObject(),
            (String) anyObject(), anyBoolean(), eq(false), anyShort(), anyLong());
    // old api client call
    doAnswer(oldCallCounter).when(nn).create((String) anyObject(), (FsPermission) anyObject(),
            (String) anyObject(), anyBoolean(), anyShort(), anyLong());

    DFSClient client = new DFSClient(null, nn, conf, null);

    boolean createParent = false;
    client.create("foo", null, false, createParent, (short) 1, 512, null, 512);
    client.create("bar", null, false, createParent, (short) 1, 512, null, 512);
    client.create("baz", null, false, createParent, (short) 1, 512, null, 512);

    // no exception was thrown, three calls to the old verison.
    assertEquals(3, oldCount.get());
    assertEquals(1, newCount.get());
}

From source file:com.github.gdrouet.scannerbenchmark.JmhBenchmark.java

/**
 * <p>//  w w  w. j  a v a2  s .c  om
 * Looking for type annotated with an annotation with annotation-detector.
 * </p>
 *
 * @throws Exception if test fails
 */
@Benchmark
public void scanAnnotatedTypeWithAnnotationDetector() throws Exception {
    final AtomicInteger count = new AtomicInteger(0);
    final AnnotationDetector.TypeReporter typeReporter = new AnnotationDetector.TypeReporter() {
        @Override
        public void reportTypeAnnotation(final Class<? extends Annotation> annotation, final String className) {
            count.incrementAndGet();
        }

        @SuppressWarnings("unchecked")
        @Override
        public Class<? extends Annotation>[] annotations() {
            return new Class[] { ANNOTATION };
        }
    };

    final AnnotationDetector cf = new AnnotationDetector(typeReporter);
    cf.detect(PACKAGE);
    LOGGER.info("{} classes annotated with {} retrieved with Annotation-Detector", count.get(),
            ANNOTATION.getName());
}

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

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

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

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

        while (true) {
            try {
                int version1 = eventStore.getCurrentVersion(streamId);
                eventStore.saveEvents(streamId, batch, version1);
                return;
            } catch (OptimisticLockingException e) {
                // retry
            }/*from  www .j  a  v  a  2s.c  o m*/
        }
    }, createRuntimeInvariantChecker(BATCH_SIZE));

    List<Event> streamEvents = eventStore.getEventsForStream(streamId);
    assertThat("number of saved events", streamEvents.size(), is(BATCH_SIZE * ITERATIONS));
    assertAtomicBatches(BATCH_SIZE, streamEvents);
    List<Event> allEvents = eventStore.getAllEvents(initialPosition);
    assertThat("global order should equal stream order", allEvents, contains(streamEvents.toArray()));
}

From source file:dk.statsbiblioteket.util.JobControllerTest.java

public void testPopAll() throws Exception {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10) {
        @Override//  ww  w  .ja va 2 s. c  o  m
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        synchronized (Thread.currentThread()) {
            Thread.currentThread().wait(10);
        }
        controller.submit(new Shout(50));
    }
    int all = controller.popAll().size();

    assertEquals("The total pops should be correct", 10, all);
    assertEquals("The callback count should be correct", 10, counter.get());
}

From source file:dk.statsbiblioteket.util.JobControllerTest.java

public void testPopTimeout() throws Exception {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10) {
        @Override/*w  w  w .j  a va2  s .com*/
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        synchronized (Thread.currentThread()) {
            Thread.currentThread().wait(10);
        }
        controller.submit(new Shout(50));
    }
    int allTimeout = controller.popAll(10, TimeUnit.MILLISECONDS).size();
    int allLeft = controller.popAll().size();

    assertTrue("Timeout popAll should be > 0 and < " + JOBS + " but was " + allTimeout,
            allTimeout > 0 && allTimeout < JOBS);
    assertEquals("The total pops should be correct", 10, allTimeout + allLeft);
    assertEquals("The callback count should be correct", 10, counter.get());
}