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.vmware.photon.controller.deployer.dcp.task.WaitForServiceTaskService.java

/**
 * This method performs document owner operations in response to a patch
 * operation./* w ww.  j  ava  2s.  c o m*/
 *
 * @param currentState
 */
private void processStartedStage(final State currentState) {
    final Service service = this;
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                failTask(throwable);
                return;
            }

            try {
                VmService.State vmState = operation.getBody(VmService.State.class);

                if (EnumUtils.isValidEnum(ContainersConfig.ContainerType.class, currentState.containerType)) {
                    ContainersConfig.ContainerType containerType = ContainersConfig.ContainerType
                            .valueOf(currentState.containerType);

                    final HealthChecker healthChecker = getHealthCheckHelperFactory()
                            .create(service, containerType, vmState.ipAddress).getHealthChecker();
                    final AtomicInteger retryCounter = new AtomicInteger(currentState.maxRetries);

                    scheduleHealthCheckQuery(currentState, healthChecker, retryCounter);
                } else {
                    // Assume success
                    sendStageProgressPatch(TaskState.TaskStage.FINISHED);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }
    };

    Operation get = Operation.createGet(UriUtils.buildUri(getHost(), currentState.vmServiceLink))
            .setCompletion(handler);

    sendRequest(get);
}

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

@Test
public void testRelease1AtATime() throws Exception {
    final int CLIENT_QTY = 10;
    final int MAX = CLIENT_QTY / 2;
    final AtomicInteger maxLeases = new AtomicInteger(0);
    final AtomicInteger activeQty = new AtomicInteger(0);
    final AtomicInteger uses = new AtomicInteger(0);

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        Future<Object> f = service.submit(new Callable<Object>() {
            @Override/*from  ww  w  . ja v  a  2s .  c o m*/
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX);
                    Lease lease = semaphore.acquire(10, TimeUnit.SECONDS);
                    Assert.assertNotNull(lease);
                    uses.incrementAndGet();
                    try {
                        synchronized (maxLeases) {
                            int qty = activeQty.incrementAndGet();
                            if (qty > maxLeases.get()) {
                                maxLeases.set(qty);
                            }
                        }

                        Thread.sleep(500);
                    } finally {
                        activeQty.decrementAndGet();
                        lease.close();
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        });
        futures.add(f);
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    Assert.assertEquals(uses.get(), CLIENT_QTY);
    Assert.assertEquals(maxLeases.get(), MAX);
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a multi-threaded benchmark.
 *
 * @param method to measure/*www  .ja  v a  2 s.  c om*/
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @param concurrency number of threads to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void multithreadedBenchmark(final String method, final String path, final int iterations,
        final int concurrency) throws IOException {
    final AtomicLong fullAggregation = new AtomicLong(0L);
    final AtomicLong serverAggregation = new AtomicLong(0L);
    final AtomicLong count = new AtomicLong(0L);
    final long perThreadCount = perThreadCount(iterations, concurrency);

    System.out.printf("Running %d iterations per thread\n", perThreadCount);

    final long testStart = System.nanoTime();

    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    final Callable<Void> worker = () -> {
        for (int i = 0; i < perThreadCount; i++) {
            Duration[] durations;

            if (method.equals("put")) {
                durations = measurePut(sizeInBytesOrNoOfDirs);
            } else if (method.equals("putDir")) {
                durations = measurePutDir(sizeInBytesOrNoOfDirs);
            } else {
                durations = measureGet(path);
            }

            long fullLatency = durations[0].toMillis();
            long serverLatency = durations[1].toMillis();
            fullAggregation.addAndGet(fullLatency);
            serverAggregation.addAndGet(serverLatency);

            System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(),
                    fullLatency, serverLatency, Thread.currentThread().getName());
        }

        return null;
    };

    final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e);

    final AtomicInteger threadCounter = new AtomicInteger(0);
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(handler);
        t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet()));

        return t;
    };

    ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory);

    List<Callable<Void>> workers = new ArrayList<>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        workers.add(worker);
    }

    try {
        List<Future<Void>> futures = executor.invokeAll(workers);

        boolean completed = false;
        while (!completed) {
            try (Stream<Future<Void>> stream = futures.stream()) {
                completed = stream.allMatch((f) -> f.isDone() || f.isCancelled());

                if (!completed) {
                    Thread.sleep(CHECK_INTERVAL);
                }
            }
        }

    } catch (InterruptedException e) {
        return;
    } finally {
        System.err.println("Shutting down the thread pool");
        executor.shutdown();
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation.get() / iterations);
    final long serverAverage = Math.round(serverAggregation.get() / iterations);
    final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis();

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", totalTime);
    System.out.printf("Total invocations: %d\n", count.get());
}