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

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

Introduction

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

Prototype

public AtomicInteger(int initialValue) 

Source Link

Document

Creates a new AtomicInteger with the given initial value.

Usage

From source file:com.intel.cosbench.driver.generator.RangeIntGenerator.java

private synchronized void init(int all) {
    if (cursors != null)
        return;/*from   w  w  w .j av  a 2  s . co  m*/

    this.cursors = new AtomicInteger[all];

    for (int i = 0; i < all; i++) {
        cursors[i] = new AtomicInteger(0);
    }
}

From source file:cz.cvut.kbss.jsonld.jackson.serialization.JacksonJsonWriterTest.java

@Test(expected = IllegalArgumentException.class)
public void writeNumberInvalidThrowsIllegalArgumentException() throws Exception {
    final AtomicInteger number = new AtomicInteger(1);
    writer.writeNumber(number);//from   ww  w .j a v  a  2 s  . c o  m
}

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

@Test
public void testKilledServerWithEnsembleProvider() throws Exception {
    final int CLIENT_QTY = 10;
    final Timing timing = new Timing();
    final String PATH = "/foo/bar/lock";

    ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    TestingCluster cluster = new TestingCluster(3);
    try {/*  www.  j a  v  a  2 s.  c om*/
        cluster.start();

        final AtomicReference<String> connectionString = new AtomicReference<String>(
                cluster.getConnectString());
        final EnsembleProvider provider = new EnsembleProvider() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public String getConnectionString() {
                return connectionString.get();
            }

            @Override
            public void close() throws IOException {
            }
        };

        final Semaphore acquiredSemaphore = new Semaphore(0);
        final AtomicInteger acquireCount = new AtomicInteger(0);
        final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY);
        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider)
                            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
                            .retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
                    try {
                        final Semaphore suspendedSemaphore = new Semaphore(0);
                        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
                            @Override
                            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                                if ((newState == ConnectionState.SUSPENDED)
                                        || (newState == ConnectionState.LOST)) {
                                    suspendedLatch.countDown();
                                    suspendedSemaphore.release();
                                }
                            }
                        });

                        client.start();

                        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1);

                        while (!Thread.currentThread().isInterrupted()) {
                            Lease lease = null;
                            try {
                                lease = semaphore.acquire();
                                acquiredSemaphore.release();
                                acquireCount.incrementAndGet();
                                suspendedSemaphore.acquire();
                            } catch (Exception e) {
                                // just retry
                            } finally {
                                if (lease != null) {
                                    acquireCount.decrementAndGet();
                                    IOUtils.closeQuietly(lease);
                                }
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        Assert.assertEquals(1, acquireCount.get());

        cluster.close();
        timing.awaitLatch(suspendedLatch);
        timing.forWaiting().sleepABit();
        Assert.assertEquals(0, acquireCount.get());

        cluster = new TestingCluster(3);
        cluster.start();

        connectionString.set(cluster.getConnectString());
        timing.forWaiting().sleepABit();

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(1, acquireCount.get());
    } finally {
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
        IOUtils.closeQuietly(cluster);
    }
}

From source file:com.indeed.lsmtree.recordcache.StandalonePersistentRecordCache.java

private StandalonePersistentRecordCache(final Store<K, V> index, final File checkpointDir) throws IOException {
    this.index = index;
    indexUpdateFunctions = new RecordLogDirectoryPoller.Functions() {

        AtomicLong indexPutTime = new AtomicLong(0);

        AtomicLong indexDeleteTime = new AtomicLong(0);

        AtomicInteger indexPuts = new AtomicInteger(0);

        AtomicInteger indexDeletes = new AtomicInteger(0);

        AtomicInteger count = new AtomicInteger(0);

        @Override/*w ww  .  j a  va 2s  .c om*/
        public void process(final long position, Operation op) throws IOException {

            count.incrementAndGet();
            if (count.get() % 1000 == 0) {
                final int puts = indexPuts.get();
                if (log.isDebugEnabled() && puts > 0) {
                    log.debug("avg index put time: " + indexPutTime.get() / puts / 1000d + " us");
                }
                final int deletes = indexDeletes.get();
                if (log.isDebugEnabled() && deletes > 0) {
                    log.debug("avg index delete time: " + indexDeleteTime.get() / deletes / 1000d + " us");
                }
            }

            if (op.getClass() == Put.class) {
                final Put<K, V> put = (Put) op;
                final long start = System.nanoTime();
                synchronized (index) {
                    index.put(put.getKey(), put.getValue());
                }
                indexPutTime.addAndGet(System.nanoTime() - start);
                indexPuts.incrementAndGet();
            } else if (op.getClass() == Delete.class) {
                final Delete<K> delete = (Delete) op;
                for (K k : delete.getKeys()) {
                    final long start = System.nanoTime();
                    synchronized (index) {
                        index.delete(k);
                    }
                    indexDeleteTime.addAndGet(System.nanoTime() - start);
                    indexDeletes.incrementAndGet();
                }
            } else if (op.getClass() == Checkpoint.class) {
                final Checkpoint checkpoint = (Checkpoint) op;
                if (checkpointDir != null) {
                    sync();
                    index.checkpoint(new File(checkpointDir, String.valueOf(checkpoint.getTimestamp())));
                }
            } else {
                log.warn("operation class unknown");
            }
        }

        @Override
        public void sync() throws IOException {
            final long start = System.nanoTime();
            index.sync();
            log.debug("sync time: " + (System.nanoTime() - start) / 1000d + " us");
        }
    };
}

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/* ww  w .  ja va  2  s  . co  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.ujorm.orm.support.UjormTransactionManager.java

/**
 *
 * @return true pokud je na zacatku deep 0 tedy jde o prvni vstup do sluzebni vrstvy
 */// www . jav a2s. com
private boolean incCalling() {
    if (deep == null) {
        deep = new AtomicInteger(1);
        return true;
    } else {
        deep.incrementAndGet();
        return false;
    }
}

From source file:strat.mining.multipool.stats.service.impl.RequestStatsLoggingServiceImpl.java

@Override
public void donnatorRequest(String bitcoinAddress) {
    AtomicInteger counter = donatorsRequests.get(bitcoinAddress);
    if (counter == null) {
        counter = new AtomicInteger(0);
        donatorsRequests.put(bitcoinAddress, counter);
    }/*from  w ww  .  j  av a2  s.  com*/
    counter.incrementAndGet();
}

From source file:net.nfpj.webcounter.dm.MemCounterDM.java

@Override
public Counter increment(String name, boolean createIfNotExist) {
    if (name == null || name.isEmpty()) {
        throw new NullPointerException("Name cannot be null");
    }//from  ww w  .  j  a  v a2 s.com
    AtomicInteger ai = counters.get(name);
    if (ai == null) {
        if (createIfNotExist) {
            AtomicInteger existing = counters.putIfAbsent(name, ai = new AtomicInteger(0));
            if (existing != null) {
                ai = existing;
            }
        } else {
            return null;
        }
    }
    return new Counter(name, ai.incrementAndGet());
}

From source file:com.flipkart.bifrost.ListenTest.java

@Test
public void testSendReceive() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    Connection connection = new Connection(Lists.newArrayList("localhost"), "guest", "guest");
    connection.start();/* ww  w. java2  s.  c  o  m*/

    BifrostExecutor<Void> executor = BifrostExecutor.<Void>builder(TestAction.class).connection(connection)
            .objectMapper(mapper).requestQueue("bifrost-send").responseQueue("bifrost-recv").concurrency(20)
            .executorService(Executors.newFixedThreadPool(20)).build();

    BifrostRemoteCallExecutionServer<Void> executionServer = BifrostRemoteCallExecutionServer
            .<Void>builder(TestAction.class).objectMapper(mapper).connection(connection).concurrency(20)
            .requestQueue("bifrost-send").build();
    executionServer.start();

    long startTime = System.currentTimeMillis();
    AtomicInteger counter = new AtomicInteger(0);
    int requestCount = 1000000;
    CompletionService<Void> ecs = new ExecutorCompletionService<>(Executors.newFixedThreadPool(50));
    List<Future<Void>> futures = Lists.newArrayListWithCapacity(requestCount);
    for (int i = 0; i < requestCount; i++) {
        futures.add(ecs.submit(new ServiceCaller(executor, counter)));
    }
    for (int i = 0; i < requestCount; i++) {
        try {
            ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    while (counter.get() != requestCount)
        ;
    System.out.println(
            String.format("Completed: %d in %d ms", counter.get(), (System.currentTimeMillis() - startTime)));
    executor.shutdown();
    executionServer.stop();
    connection.stop();

    Assert.assertEquals(requestCount, counter.get());
}

From source file:io.cloudslang.orchestrator.services.OrchestratorDispatcherServiceImpl.java

private void dispatch(List<? extends Serializable> messages) {
    Validate.notNull(messages, "Messages list is null");

    if (logger.isDebugEnabled())
        logger.debug("Dispatching " + messages.size() + " messages");
    long t = System.currentTimeMillis();
    final AtomicInteger messagesCounter = new AtomicInteger(0);

    dispatch(messages, ExecutionMessage.class, new Handler<ExecutionMessage>() {
        @Override//from   w w w  .j a  v  a 2s  .  co  m
        public void handle(List<ExecutionMessage> messages) {
            messagesCounter.addAndGet(messages.size());
            queueDispatcher.dispatch(messages);
        }
    });

    dispatch(messages, SplitMessage.class, new Handler<SplitMessage>() {
        @Override
        public void handle(List<SplitMessage> messages) {
            messagesCounter.addAndGet(messages.size());
            splitJoinService.split(messages);
        }
    });

    t = System.currentTimeMillis() - t;
    if (logger.isDebugEnabled())
        logger.debug("Dispatching " + messagesCounter.get() + " messages is done in " + t + " ms");
    if (messages.size() > messagesCounter.get()) {
        logger.warn((messages.size() - messagesCounter.get())
                + " messages were not being dispatched, since unknown type");
    }
}