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

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

Introduction

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

Prototype

public final int getAndIncrement() 

Source Link

Document

Atomically increments the current value, with memory effects as specified by VarHandle#getAndAdd .

Usage

From source file:org.elasticsearch.logstash.Server.java

public void start() throws InterruptedException {

    long start = System.nanoTime();

    AtomicInteger counter = new AtomicInteger(1);

    for (int i = 0; i < messageCount; i++) {
        /* wait for input -- e.g. wait on a NETTY pipeline input */
        //        JokeResource jokeResource = restTemplate.getForObject("http://api.icndb.com/jokes/random", JokeResource.class);

        final String message = String.format("message: %d", counter.getAndIncrement());
        inputReactor.notify(Pipeline.Stage.input, Event.wrap(message));
    }//w  ww. ja  v  a2s  .  c o  m

    latch.await();
    long elapsed = System.nanoTime() - start;

    System.out.println("Elapsed time: " + elapsed + "ns");
    System.out.println("Average pipeline process time per message: " + elapsed / messageCount + "ns");
}

From source file:org.commonjava.maven.plugins.betterdep.PathsGoal.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (HAS_RUN) {
        getLog().info("Dependency paths goal has already run. Skipping.");
        return;//from   ww  w  . j a v  a2 s.  c o  m
    }

    HAS_RUN = true;

    initDepgraph(true);

    final String[] rawGavs = toProjects.split("\\s*,\\s*");
    toGas = new HashSet<ProjectRef>(rawGavs.length);
    for (final String rawGav : rawGavs) {
        toGas.add(project(rawGav));
    }

    GraphComposition comp = GraphCompositionBuilder.newGraphCompositionBuilder().withGraph(
            GraphDescriptionBuilder.newGraphDescriptionBuilder().withFilter(filter).withRoots(roots).build())
            .build();

    PathsRequest request = PathsRequestBuilder.newPathsRecipeBuilder().withResolve(true)
            .withWorkspaceId(WORKSPACE_ID).withSource(MavenLocationExpander.EXPANSION_TARGET).withGraphs(comp)
            .withTargets(toGas).build();

    getLog().info("Resolving paths to:\n\n  " + join(toGas, "\n  ") + "\n\nIn scope: " + scope + "\n");

    ProjectPathsResult result;
    try {
        result = carto.getGrapher().getPaths(request);
    } catch (CartoDataException e) {
        throw new MojoExecutionException("Failed to traverse '" + roots + "' looking for paths to: " + toGas
                + ". Reason: " + e.getMessage(), e);
    } catch (CartoRequestException e) {
        throw new MojoExecutionException("Failed to traverse '" + roots + "' looking for paths to: " + toGas
                + ". Reason: " + e.getMessage(), e);
    }

    final StringBuilder sb = new StringBuilder();
    if (result != null && result.getProjects() != null) {
        AtomicInteger count = new AtomicInteger(0);
        result.getProjects().forEach((gav, pathSet) -> {
            if (pathSet.getPaths() != null) {
                for (ProjectPath path : pathSet.getPaths()) {
                    sb.append(count.getAndIncrement()).append(". ");
                    printPath(sb, path);
                }

                sb.append("\n\n");
            }
        });

        sb.append("\n\n").append(count.incrementAndGet()).append(" paths found.\n\n");
    }

    if (sb.length() < 1) {
        sb.append("\n\nNo paths found!\n\n");
    }

    write(sb);
}

From source file:org.dataconservancy.dcs.util.DigestNotificationOutputStreamTest.java

@Test
public void listenerNotifiedOnceTest() throws IOException, NoSuchAlgorithmException {
    final AtomicInteger count = new AtomicInteger(0);
    final OutputStream s = new DigestNotificationOutputStream(new ByteArrayOutputStream(),
            MessageDigest.getInstance("MD5"), new DigestListener() {
                @Override//from   ww  w .jav  a 2 s. c o m
                public void notify(byte[] digestValue) throws IOException {
                    count.getAndIncrement();
                }
            });

    IOUtils.copy(new ByteArrayInputStream(CONTENT.getBytes()), s);
    assertEquals(0, count.intValue());
    s.close();
    assertEquals(1, count.intValue());
    s.close();
    assertEquals(1, count.intValue());
}

From source file:lenscorrection.Distortion_Correction.java

static protected void extractSIFTPointsThreaded(final int index, final List<Feature>[] siftFeatures,
        final List<PointMatch>[] inliers, final AbstractAffineModel2D<?>[] models) {

    // save all matching candidates
    final List<PointMatch>[] candidates = new List[siftFeatures.length - 1];

    final Thread[] threads = MultiThreading.newThreads();
    final AtomicInteger ai = new AtomicInteger(0); // start at second
    // slice/*from   w  w w.  j  a  va 2s.c om*/

    for (int ithread = 0; ithread < threads.length; ++ithread) {
        threads[ithread] = new Thread() {
            @Override
            public void run() {
                setPriority(Thread.NORM_PRIORITY);

                for (int j = ai.getAndIncrement(); j < candidates.length; j = ai.getAndIncrement()) {
                    final int i = (j < index ? j : j + 1);
                    candidates[j] = FloatArray2DSIFT.createMatches(siftFeatures[index], siftFeatures[i], 1.5f,
                            null, Float.MAX_VALUE, 0.5f);
                }
            }
        };
    }

    MultiThreading.startAndJoin(threads);

    // get rid of the outliers and save the rigid transformations to match
    // the inliers

    final AtomicInteger ai2 = new AtomicInteger(0);
    for (int ithread = 0; ithread < threads.length; ++ithread) {
        threads[ithread] = new Thread() {
            @Override
            public void run() {
                setPriority(Thread.NORM_PRIORITY);
                for (int i = ai2.getAndIncrement(); i < candidates.length; i = ai2.getAndIncrement()) {

                    final List<PointMatch> tmpInliers = new ArrayList<PointMatch>();
                    // RigidModel2D m =
                    // RigidModel2D.estimateBestModel(candidates.get(i),
                    // tmpInliers, sp.min_epsilon, sp.max_epsilon,
                    // sp.min_inlier_ratio);

                    final AbstractAffineModel2D<?> m;
                    switch (sp.expectedModelIndex) {
                    case 0:
                        m = new TranslationModel2D();
                        break;
                    case 1:
                        m = new RigidModel2D();
                        break;
                    case 2:
                        m = new SimilarityModel2D();
                        break;
                    case 3:
                        m = new AffineModel2D();
                        break;
                    default:
                        return;
                    }

                    boolean modelFound = false;
                    try {
                        modelFound = m.filterRansac(candidates[i], tmpInliers, 1000, sp.maxEpsilon,
                                sp.minInlierRatio, 10);
                    } catch (final NotEnoughDataPointsException e) {
                        modelFound = false;
                    }

                    if (modelFound)
                        IJ.log("Model found:\n  " + candidates[i].size() + " candidates\n  " + tmpInliers.size()
                                + " inliers\n  " + String.format("%.2f", m.getCost())
                                + "px average displacement");
                    else
                        IJ.log("No Model found.");

                    inliers[index * (sp.numberOfImages - 1) + i] = tmpInliers;
                    models[index * (sp.numberOfImages - 1) + i] = m;
                    // System.out.println("**** MODEL ADDED: " +
                    // (index*(sp.numberOfImages-1)+i));
                }

            }
        };
    }
    MultiThreading.startAndJoin(threads);

}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {//  w w  w . j av a  2  s.  co  m
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}

From source file:org.jboss.pnc.coordinator.test.event.StatusUpdatesTest.java

public BuildSetTask createBuildSetTask(BuildConfigurationSet buildConfigurationSet, User user)
        throws CoreException {
    BuildTasksInitializer buildTasksInitializer = new BuildTasksInitializer(datastoreAdapter, 1L);
    AtomicInteger atomicInteger = new AtomicInteger(1);

    BuildOptions buildOptions = new BuildOptions();
    buildOptions.setRebuildMode(RebuildMode.FORCE);
    return buildTasksInitializer.createBuildSetTask(buildConfigurationSet, user, buildOptions,
            () -> atomicInteger.getAndIncrement(), buildQueue.getUnfinishedTasks());
}

From source file:com.vmware.admiral.adapter.docker.service.DockerNetworkAdapterService.java

private void processCreateNetwork(RequestContext context, int retriesCount) {
    AssertUtil.assertNotNull(context.networkState, "networkState");
    AssertUtil.assertNotEmpty(context.networkState.name, "networkState.name");

    CommandInput createCommandInput = context.commandInput
            .withPropertyIfNotNull(DOCKER_CONTAINER_NETWORK_NAME_PROP_NAME, context.networkState.name);
    if (context.networkState.driver != null && !context.networkState.driver.isEmpty()) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_DRIVER_PROP_NAME, context.networkState.driver);
    } else {//from w w w . jav a  2  s  .  c  o m
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_DRIVER_PROP_NAME, DOCKER_NETWORK_TYPE_DEFAULT);
    }

    if (context.networkState.options != null && !context.networkState.options.isEmpty()) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_OPTIONS_PROP_NAME,
                context.networkState.options);
    }

    if (context.networkState.ipam != null) {
        createCommandInput.withProperty(DOCKER_CONTAINER_NETWORK_IPAM_PROP_NAME,
                DockerAdapterUtils.ipamToMap(context.networkState.ipam));
    }

    context.executor.createNetwork(createCommandInput, (op, ex) -> {
        if (ex != null) {
            AtomicInteger retryCount = new AtomicInteger(retriesCount);
            if (RETRIABLE_HTTP_STATUSES.contains(op.getStatusCode())
                    && retryCount.getAndIncrement() < NETWORK_CREATE_RETRIES_COUNT) {
                // retry if failure is retriable
                logWarning("Create network %s failed with %s. Retries left %d", context.networkState.name,
                        Utils.toString(ex), NETWORK_CREATE_RETRIES_COUNT - retryCount.get());
                processCreateNetwork(context, retryCount.get());
            } else {
                fail(context.request, op, ex);
            }
        } else {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = op.getBody(Map.class);

            context.networkState.id = (String) body.get(DOCKER_CONTAINER_NETWORK_ID_PROP_NAME);
            inspectAndUpdateNetwork(context);
            // transition to TaskStage.FINISHED is done later, after the network state gets
            // updated
        }
    });
}

From source file:org.dataconservancy.dcs.util.DigestNotificationStreamTest.java

@Test
public void listenerNotifiedOnceTest() throws IOException, NoSuchAlgorithmException {
    final AtomicInteger count = new AtomicInteger(0);
    final InputStream s = new DigestNotificationStream(new ByteArrayInputStream(CONTENT.getBytes()),
            MessageDigest.getInstance("MD5"), new DigestListener() {
                @Override//w ww .  ja va 2s  .  c  om
                public void notify(byte[] digestValue) throws IOException {
                    count.getAndIncrement();
                }
            });

    assertEquals(0, count.intValue());
    IOUtils.copy(s, new NullOutputStream());
    assertEquals(1, count.intValue());
    s.close();
    assertEquals(1, count.intValue());
}

From source file:org.moe.gradle.AbstractMoePlugin.java

protected <T extends AbstractBaseTask> void addRule(Class<T> taskClass, String description,
        List<TaskParams> params, AbstractMoePlugin plugin) {
    // Prepare constants
    final String TASK_NAME = taskClass.getSimpleName();
    final String ELEMENTS_DESC = params.stream().map(p -> "<" + p.getName() + ">")
            .collect(Collectors.joining());
    final String PATTERN = MOE + ELEMENTS_DESC + TASK_NAME;

    // Add rule// www .  j  av a 2 s  . c  om
    getProject().getTasks().addRule("Pattern: " + PATTERN + ": " + description, new RuleClosure(getProject()) {
        @Override
        public @Nullable Task doCall(@NotNull String taskName) {
            Require.nonNull(taskName);

            // Check for prefix, suffix and get elements in-between
            List<String> elements = StringUtils.getElemsInRule(taskName, MOE, TASK_NAME);

            // Prefix or suffix failed
            if (elements == null) {
                return null;
            }

            // Check number of elements
            TaskUtils.assertSize(elements, params.size(), ELEMENTS_DESC);

            // Check element values & configure task on success
            final AtomicInteger pIndex = new AtomicInteger();
            final Object[] objects = params.stream()
                    .map(p -> p.getValue(plugin, elements.get(pIndex.getAndIncrement())))
                    .collect(Collectors.toList()).toArray();

            // Create task
            final T task = getProject().getTasks().create(taskName, taskClass);

            // Set group
            task.setGroup(MOE);

            // Call setup method
            ((GroovyObject) task).invokeMethod("setupMoeTask", objects);

            checkRemoteServer(task);

            return task;
        }
    });
}

From source file:org.bonej.wrapperPlugins.AnisotropyWrapper.java

private List<Vector3d> runDirectionsInParallel(final RandomAccessibleInterval<BitType> interval)
        throws ExecutionException, InterruptedException {
    final int cores = Runtime.getRuntime().availableProcessors();
    // The parallellization of the the MILPlane algorithm is a memory bound
    // problem, which is why speed gains start to drop after 5 cores. With much
    // larger 'nThreads' it slows down due to overhead. Of course '5' here is a
    // bit of a magic number, which might not hold true for all environments,
    // but we need some kind of upper bound
    final int nThreads = Math.max(5, cores);
    final ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    final Callable<Vector3d> milTask = () -> milOp.calculate(interval, randomQuaternion());
    final List<Future<Vector3d>> futures = generate(() -> milTask).limit(directions).map(executor::submit)
            .collect(toList());/*from   w  ww.java 2  s .  c o m*/
    final List<Vector3d> pointCloud = Collections.synchronizedList(new ArrayList<>(directions));
    final int futuresSize = futures.size();
    final AtomicInteger progress = new AtomicInteger();
    for (final Future<Vector3d> future : futures) {
        statusService.showProgress(progress.getAndIncrement(), futuresSize);
        pointCloud.add(future.get());
    }
    shutdownAndAwaitTermination(executor);
    return pointCloud;
}