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:alluxio.cli.MiniBenchmark.java

/**
 * @param args there are no arguments needed
 * @throws Exception if error occurs during tests
 *///from  w w w.j a  va 2s  . c om
public static void main(String[] args) throws Exception {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(-1);
    }
    if (sHelp) {
        usage();
        System.exit(0);
    }

    CommonUtils.warmUpLoop();

    for (int i = 0; i < sIterations; ++i) {
        final AtomicInteger count = new AtomicInteger(0);
        final CyclicBarrier barrier = new CyclicBarrier(sConcurrency);
        ExecutorService executorService = Executors.newFixedThreadPool(sConcurrency);
        final AtomicLong runtime = new AtomicLong(0);
        for (int j = 0; j < sConcurrency; ++j) {
            switch (sType) {
            case READ:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            readFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to read file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            case WRITE:
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeFile(barrier, runtime, count.addAndGet(1));
                        } catch (Exception e) {
                            LOG.error("Failed to write file.", e);
                            System.exit(-1);
                        }
                    }
                });
                break;
            default:
                throw new RuntimeException("Unsupported type.");
            }
        }
        executorService.shutdown();
        Preconditions.checkState(executorService.awaitTermination(1, TimeUnit.HOURS));
        double time = runtime.get() * 1.0 / sConcurrency / Constants.SECOND_NANO;
        System.out.printf("Iteration: %d; Duration: %f seconds; Aggregated throughput: %f GB/second.%n", i,
                time, sConcurrency * 1.0 * sFileSize / time / Constants.GB);
    }
}

From source file:com.github.ambry.store.DiskReformatter.java

public static void main(String[] args) throws Exception {
    VerifiableProperties properties = ToolUtils.getVerifiableProperties(args);
    DiskReformatterConfig config = new DiskReformatterConfig(properties);
    StoreConfig storeConfig = new StoreConfig(properties);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties);
    ServerConfig serverConfig = new ServerConfig(properties);
    ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory,
            clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath);
    try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) {
        StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(
                serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry());
        StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap);
        DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort);
        if (dataNodeId == null) {
            throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - "
                    + config.datanodeHostname + ":" + config.datanodePort);
        }/* w  ww . j a v  a  2  s .c o  m*/
        DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST,
                config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(),
                storeKeyConverterFactory.getStoreKeyConverter());
        AtomicInteger exitStatus = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length);
        for (int i = 0; i < config.diskMountPaths.length; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI]));
                    latch.countDown();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            };
            Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true);
            thread.setUncaughtExceptionHandler((t, e) -> {
                exitStatus.set(1);
                logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e);
                latch.countDown();
            });
            thread.start();
        }
        latch.await();
        System.exit(exitStatus.get());
    }
}

From source file:Main.java

/**
 * Generate a value suitable for use in {@ link #setId(int)}.
 * This value will not collide with ID values generated at build time by aapt for R.id.
 * http://stackoverflow.com/a/15442997/151957
 * @return a generated ID value/*w w w . ja  v a 2s  . c o  m*/
 */
public static int generateViewId() {
    AtomicInteger sNextGeneratedId = new AtomicInteger(10001);

    for (;;) {
        final int result = sNextGeneratedId.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF)
            newValue = 1; // Roll over to 1, not 0.
        if (sNextGeneratedId.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

From source file:Main.java

public static ExecutorService createEventsUnorderedDeliveryExecutor() {
    return Executors.newCachedThreadPool(new ThreadFactory() {
        private AtomicInteger cnt = new AtomicInteger(0);

        @Override//  w ww . j  a  v  a  2s .  co m
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Unordered Events Thread-" + cnt.incrementAndGet());
            t.setDaemon(true);
            // XXX perhaps set uncaught exception handler here according to resilience strategy
            return t;
        }
    });
}

From source file:Main.java

public static ExecutorService createEventsOrderedDeliveryExecutor() {
    return Executors.newSingleThreadExecutor(new ThreadFactory() {
        private AtomicInteger cnt = new AtomicInteger(0);

        @Override// w  w w  . j a v  a 2 s . com
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Ordered Events Thread-" + cnt.incrementAndGet());
            t.setDaemon(true);
            // XXX perhaps set uncaught exception handler here according to resilience strategy
            return t;
        }
    });
}

From source file:Main.java

public static ScheduledExecutorService createStatisticsExecutor() {
    return Executors.newScheduledThreadPool(Integer.getInteger(ORG_EHCACHE_STATISTICS_EXECUTOR_POOL_SIZE, 1),
            new ThreadFactory() {
                private AtomicInteger cnt = new AtomicInteger(0);

                @Override/*from w  ww. j av  a  2s .  c o  m*/
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "Statistics Thread-" + cnt.incrementAndGet());
                    t.setDaemon(true);
                    return t;
                }
            });
}

From source file:org.eclipse.swt.snippets.Snippet366.java

private static void makeOrientationGroup() {
    Group orientationGroup = new Group(shell, SWT.None);
    orientationGroup.setLayout(new RowLayout());
    orientationGroup.setText("Orientation group");

    final AtomicInteger prevDir = new AtomicInteger(0);
    final Button alignmentButton = new Button(orientationGroup, SWT.ARROW | SWT.RIGHT);
    alignmentButton.addListener(SWT.MouseDown, event -> {
        switch (prevDir.get()) {
        case 0://from  www.  j  ava2 s .c  o  m
            alignmentButton.setOrientation(SWT.LEFT_TO_RIGHT);
            prevDir.set(1);
            break;
        case 1:
            alignmentButton.setOrientation(SWT.RIGHT_TO_LEFT);
            prevDir.set(0);
            break;
        default:
            break;
        }
    });
}

From source file:io.bifroest.names.EnumerateDrainByTypeScheme.java

private int getNextDrainIndex(String type) {
    AtomicInteger currentCount;/*from  w ww  .j  a va2s . c  o  m*/
    if (typeToDrainsNamedSoFar.containsKey(type)) {
        currentCount = typeToDrainsNamedSoFar.get(type);
    } else {
        currentCount = new AtomicInteger(0);
        typeToDrainsNamedSoFar.put(type, currentCount);
    }
    return currentCount.incrementAndGet();
}

From source file:cz.pichlik.goodsentiment.common.CSVReader.java

public void readLines(RowProcessor processor) {
    ArrayList<String> val = new ArrayList<>();
    AtomicInteger counter = new AtomicInteger(0);
    csvParser.forEach((r) -> {/*from w w w  .jav  a 2s .  c  o m*/
        try {
            r.forEach((s) -> val.add(s));
            processor.accept(val, counter.getAndIncrement());
        } finally {
            val.clear();
        }
    });
}

From source file:AtomicPseudoRandom.java

public AtomicPseudoRandom(int seed) {
    this.seed = new AtomicInteger(seed);
}