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:dk.statsbiblioteket.util.JobControllerTest.java

public void testPopFinished() 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  v  a  2s.co 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 first = controller.popFinished().size();
    synchronized (Thread.currentThread()) {
        Thread.currentThread().wait(60);
    }
    int second = controller.popFinished().size();

    assertTrue("The first pop should yield some results. Got " + first, first > 0);
    assertTrue("The second pop should yield some results. Got " + second, second > 0);
    log.info("first popFinished: " + first + ", second popFinished: " + second);
    assertEquals("The total pops should be correct", 10, first + second);
    assertEquals("The callback count should be correct", 10, counter.get());
}

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

public void TestAutoEmpty() throws InterruptedException {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10, true) {
        @Override//from  w w w .j  a va  2 s .c o  m
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        controller.submit(new Shout(JOBS / 4));
        synchronized (Thread.currentThread()) {
            Thread.currentThread().wait(JOBS / 10);
        }
    }
    synchronized (Thread.currentThread()) {
        Thread.currentThread().wait(JOBS / 4 + 1);
    }
    assertEquals("The auto removed count should be all the jobs", JOBS, counter.get());
    assertEquals("The JobController should be empty", 0, controller.getTaskCount());
}

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

public void TestAutoEmptyMultiPoll() throws InterruptedException {
    final int JOBS = 10;
    final AtomicInteger counter = new AtomicInteger(0);
    JobController<Long> controller = new JobController<Long>(10, true) {
        @Override/*from w  w  w.  ja  v  a 2 s .co  m*/
        protected void afterExecute(Future<Long> finished) {
            counter.incrementAndGet();
        }
    };
    for (int i = 0; i < JOBS; i++) {
        controller.submit(new Shout(JOBS / 4));
        synchronized (Thread.currentThread()) {
            Thread.currentThread().wait(JOBS / 10);
        }
    }
    int popped = controller.popAll().size();
    assertEquals("The auto removed count should be all the jobs", JOBS, counter.get());
    assertEquals("The JobController should be empty", 0, controller.getTaskCount());
    assertTrue("The number of explicit popped jobs should be > 0 and < " + JOBS + " but was " + popped,
            popped > 0 && popped < JOBS);
}

From source file:org.apache.cayenne.access.dbsync.BaseSchemaUpdateStrategy_ConcurrencyTest.java

@Test
public void testUpdateSchema_Concurrency() throws InterruptedException, ExecutionException, TimeoutException {

    final AtomicInteger counter = new AtomicInteger();
    final AtomicBoolean errors = new AtomicBoolean(false);

    final BaseSchemaUpdateStrategy strategy = new BaseSchemaUpdateStrategy() {
        @Override/*w ww .  j a  va  2  s  .  com*/
        protected void processSchemaUpdate(DataNode dataNode) throws SQLException {
            counter.incrementAndGet();
        }
    };

    Collection<Future<?>> tasks = new ArrayList<>();

    for (int i = 0; i < 20; i++) {
        tasks.add(threadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    strategy.updateSchema(dataNode);
                } catch (Throwable e) {
                    LOGGER.error("error in test", e);
                    errors.set(true);
                }
            }
        }));
    }

    for (Future<?> f : tasks) {
        f.get(1, TimeUnit.SECONDS);
    }

    assertFalse(errors.get());
    assertEquals(1, counter.get());
}

From source file:com.vladmihalcea.mongo.dao.ProductRepositoryIT.java

@Test
public void testRetries() throws InterruptedException {
    Product product = new Product();
    product.setId(123L);/*w w  w  . ja v a  2  s . c  o m*/
    product.setName("Tv");
    productRepository.save(product);
    Product savedProduct = productRepository.findOne(123L);
    assertEquals(savedProduct, product);

    final int threadsNumber = 10;

    final AtomicInteger atomicInteger = new AtomicInteger();
    final CountDownLatch startLatch = new CountDownLatch(threadsNumber + 1);
    final CountDownLatch endLatch = new CountDownLatch(threadsNumber + 1);

    for (; atomicInteger.get() < threadsNumber; atomicInteger.incrementAndGet()) {
        final long index = (long) atomicInteger.get() * threadsNumber;
        LOGGER.info("Scheduling thread index {}", index);
        Thread testThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startLatch.countDown();
                    startLatch.await();
                    productService.updateName(123L, UUID.randomUUID().toString());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.error("Exception thrown!", e);
                } finally {
                    endLatch.countDown();
                }
            }
        });
        testThread.start();
    }
    startLatch.countDown();
    LOGGER.info("Waiting for threads to be done");
    endLatch.countDown();
    endLatch.await();
    LOGGER.info("Threads are done");
}

From source file:de.tudarmstadt.lt.seg.sentence.SentenceSplitterTest.java

@Test
public void ruleSplitterTest() {
    final AtomicInteger n = new AtomicInteger(0);
    ISentenceSplitter s = new RuleSplitter().initParam("default", false).init(TEST_TEXT);
    System.out.format("+++ %s +++ %n", s.getClass().getName());
    s.forEach(seg -> {/*w w  w .  ja va 2 s  .  c o  m*/
        if (seg.type == SegmentType.SENTENCE)
            n.incrementAndGet();
        System.out.println(seg);
    });
    System.out.println("+++");
    s.init(TokenizerTest.TEST_TEXT);
    s.forEach(seg -> {
        if (seg.type == SegmentType.SENTENCE)
            n.incrementAndGet();
        System.out.println(seg);
    });
    System.out.format("%d sentences.%n", n.get());
}

From source file:com.all.mobile.web.services.StatsService.java

public void logPlaycount(String trackId) {
    AtomicInteger counter = bufferedStats.get(trackId);
    if (counter == null) {
        counter = new AtomicInteger();
    }/*from w  w  w. ja  v  a2 s  . c  om*/
    counter.incrementAndGet();
    bufferedStats.put(trackId, counter);
}

From source file:com.rationaldevelopers.oss.service.CacheService.java

@Scheduled(fixedRate = 60000)
public void trueUpCache() {
    if (!lock.isLocked()) {
        lock.lock();//  w  ww .  j a v a  2 s . c o m
        try {
            LOGGER.info("Running Timed Task");
            final Iterable<SimpleItem> all = simpleItemService.findAll();
            final AtomicInteger itemsUpdated = new AtomicInteger(0);
            StreamSupport.stream(all.spliterator(), false).filter(i -> !cache.containsKey(i.getSid())
                    || cache.containsKey(i.getSid()) && !cache.get(i.getSid()).equals(i)).forEach(i -> {
                        cache.put(i.getSid(), i);
                        itemsUpdated.incrementAndGet();
                    });
            LOGGER.info("Total Items Updated: {}", itemsUpdated.get());
        } finally {
            lock.unlock();
        }
    }
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowTraversalToIterateInDifferentThreadThanOriginallyEvaluatedWithoutAutoCommit()
        throws Exception {
    // this test sort of simulates Gremlin Server interaction where a Traversal is eval'd in one Thread, but
    // then iterated in another.  this basically tests the state of the Gremlin Server GremlinExecutor when
    // being used in session mode
    final ExecutorService evalExecutor = Executors.newSingleThreadExecutor(testingThreadFactory);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().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();/*ww w  .ja v a 2  s  .c o m*/

    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.conductor.core.execution.TestWorkflowExecutor.java

@Test
public void test() throws Exception {

    AtomicBoolean httpTaskExecuted = new AtomicBoolean(false);
    AtomicBoolean http2TaskExecuted = new AtomicBoolean(false);

    new Wait();//from  www. java  2s  . c  o m
    new WorkflowSystemTask("HTTP") {
        @Override
        public boolean isAsync() {
            return true;
        }

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            httpTaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    new WorkflowSystemTask("HTTP2") {

        @Override
        public void start(Workflow workflow, Task task, WorkflowExecutor executor) throws Exception {
            http2TaskExecuted.set(true);
            task.setStatus(Status.COMPLETED);
            super.start(workflow, task, executor);
        }

    };

    Workflow workflow = new Workflow();
    workflow.setWorkflowId("1");

    TestConfiguration config = new TestConfiguration();
    MetadataDAO metadata = mock(MetadataDAO.class);
    ExecutionDAO edao = mock(ExecutionDAO.class);
    QueueDAO queue = mock(QueueDAO.class);
    ObjectMapper om = new ObjectMapper();

    WorkflowExecutor executor = new WorkflowExecutor(metadata, edao, queue, om, config);
    List<Task> tasks = new LinkedList<>();

    WorkflowTask taskToSchedule = new WorkflowTask();
    taskToSchedule.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule.setType("HTTP");

    WorkflowTask taskToSchedule2 = new WorkflowTask();
    taskToSchedule2.setWorkflowTaskType(Type.USER_DEFINED);
    taskToSchedule2.setType("HTTP2");

    WorkflowTask wait = new WorkflowTask();
    wait.setWorkflowTaskType(Type.WAIT);
    wait.setType("WAIT");
    wait.setTaskReferenceName("wait");

    Task task1 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>(), null,
            0);
    Task task2 = SystemTask.waitTask(workflow, IDGenerator.generate(), taskToSchedule, new HashMap<>());
    Task task3 = SystemTask.userDefined(workflow, IDGenerator.generate(), taskToSchedule2, new HashMap<>(),
            null, 0);

    tasks.add(task1);
    tasks.add(task2);
    tasks.add(task3);

    when(edao.createTasks(tasks)).thenReturn(tasks);
    AtomicInteger startedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            startedTaskCount.incrementAndGet();
            return null;
        }
    }).when(edao).updateTask(any());

    AtomicInteger queuedTaskCount = new AtomicInteger(0);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            String queueName = invocation.getArgumentAt(0, String.class);
            System.out.println(queueName);
            queuedTaskCount.incrementAndGet();
            return null;
        }
    }).when(queue).push(any(), any(), anyInt());

    boolean stateChanged = executor.scheduleTask(workflow, tasks);
    assertEquals(2, startedTaskCount.get());
    assertEquals(1, queuedTaskCount.get());
    assertTrue(stateChanged);
    assertFalse(httpTaskExecuted.get());
    assertTrue(http2TaskExecuted.get());
}