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.espertech.esper.dataflow.core.EPDataFlowInstanceImpl.java

public synchronized void start() {
    checkExecCompleteState();// w  w w. ja  v  a 2 s. c  o  m
    checkExecCancelledState();
    checkExecRunningState();

    callOperatorOpen();

    final AtomicInteger countdown = new AtomicInteger(sourceRunnables.size());
    threads = new ArrayList<Thread>();
    for (int i = 0; i < sourceRunnables.size(); i++) {
        GraphSourceRunnable runnable = sourceRunnables.get(i);
        String threadName = "esper." + dataFlowName + "-" + i;
        Thread thread = new Thread(runnable, threadName);
        thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
        thread.setDaemon(true);
        runnable.addCompletionListener(new CompletionListener() {
            public void completed() {
                int remaining = countdown.decrementAndGet();
                if (remaining == 0) {
                    EPDataFlowInstanceImpl.this.completed();
                }
            }
        });
        threads.add(thread);
        thread.start();
    }
    setState(EPDataFlowState.RUNNING);
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java

@Test
public void testPutListener() throws Exception {
    final int itemQty = 10;

    DistributedQueue<TestQueueItem> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*from   w  ww. jav a2s  .c om*/
    try {
        BlockingQueueConsumer<TestQueueItem> consumer = new BlockingQueueConsumer<TestQueueItem>(
                Mockito.mock(ConnectionStateListener.class));

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue();
        queue.start();

        QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0);

        final AtomicInteger listenerCalls = new AtomicInteger(0);
        QueuePutListener<TestQueueItem> listener = new QueuePutListener<TestQueueItem>() {
            @Override
            public void putCompleted(TestQueueItem item) {
                listenerCalls.incrementAndGet();
            }

            @Override
            public void putMultiCompleted(MultiItem<TestQueueItem> items) {
            }
        };
        queue.getPutListenerContainer().addListener(listener);

        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(producer);

        int iteration = 0;
        while (consumer.size() < itemQty) {
            Assert.assertTrue(++iteration < 10);
            Thread.sleep(1000);
        }

        int i = 0;
        for (TestQueueItem item : consumer.getItems()) {
            Assert.assertEquals(item.str, Integer.toString(i++));
        }

        Assert.assertEquals(listenerCalls.get(), itemQty);
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.appleframework.monitor.model.MetricDog.java

private void resetFireTimes(String projectName, String metricName) {
    String metricNotifyKey = projectName + "_" + metricName;
    metricFireTimes.put(metricNotifyKey, new AtomicInteger(0));
}

From source file:com.adobe.acs.commons.mcp.impl.processes.DeepPrune.java

private void purgeJobs(ActionManager manager) {
    ActionBatch batch = new ActionBatch(manager, batchSize);
    batch.setRetryCount(retryCount);//from w  w w. jav a2 s  .  c  o  m
    batch.setRetryWait(retryWait);
    TreeFilteringResourceVisitor visitor = new TreeFilteringResourceVisitor();
    visitor.setDepthFirstMode();
    visitor.setTraversalFilter(res -> visitor.isFolder(res) && !shouldIgnore(res));
    AtomicInteger lastLevel = new AtomicInteger(0);
    visitor.setResourceVisitor((res, level) -> {
        if (level >= minPurgeDepth && !shouldIgnore(res) && folderRule.matcher.apply(res.getName())) {
            if (lastLevel.getAndSet(level) != level) {
                batch.commitBatch();
            }
            String path = res.getPath();
            batch.add(rr -> deleteResource(rr, path));
        }
    });
    visitor.setLeafVisitor((res, level) -> {
        if (!shouldIgnore(res)) {
            if (lastLevel.getAndSet(level) != level) {
                batch.commitBatch();
            }
            String path = res.getPath();
            batch.add(rr -> deleteResource(rr, path));
        }
    });
    manager.deferredWithResolver(rr -> {
        Resource res = rr.getResource(startingFolder);
        if (res != null) {
            visitor.accept(res);
        }
        batch.commitBatch();
    });
}

From source file:dk.statsbiblioteket.util.xml.XSLT.java

private static ThreadLocal<Map<String, Transformer>> createLocalMapCache() {
    return new ThreadLocal<Map<String, Transformer>>() {
        private AtomicInteger counter = new AtomicInteger(0);

        @Override//from   w  w  w  .  ja  v a 2s. c o m
        protected Map<String, Transformer> initialValue() {
            log.trace("Creating ThreadLocal localMapCache #" + counter);
            return new HashMap<String, Transformer>();
        }
    };
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testMetadataAccessFailureHandlerWithEventHandler() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

    try {/*w w w. j  a va 2 s . co m*/
        tempDirectory.toFile().setExecutable(false);

        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();

        fileMapper.put(filePath.toString(), filePath);

        final AtomicInteger numTimesFailureHandlerCalled = new AtomicInteger(0);

        try (final InputStream inputStream = Runtime.getRuntime().exec("ls -lR").getInputStream()) {
            LOG.info(IOUtils.toString(inputStream));
        }
        new MetadataAccessImpl(fileMapper.build(), new FailureEventListener() {
            @Override
            public void onFailure(final FailureEvent failureEvent) {
                numTimesFailureHandlerCalled.incrementAndGet();
                assertEquals(FailureEvent.FailureActivity.RecordingMetadata, failureEvent.doingWhat());
            }
        }, "localhost").getMetadataValue("forceAFailureByUsingANonExistentFileBecauseTheDockerImageRunsAsRoot");

        assertEquals(1, numTimesFailureHandlerCalled.get());
    } finally {
        tempDirectory.toFile().setExecutable(true);
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:de.bund.bfr.math.LeastSquaresOptimization.java

@Override
public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful,
        Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations,
        DoubleConsumer progressListener, ExecutionContext exec) throws CanceledExecutionException {
    if (exec != null) {
        exec.checkCanceled();/*from  w ww .j av a  2 s . c o m*/
    }

    progressListener.accept(0.0);

    List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues,
            nParameterSpace);
    RealVector targetVector = new ArrayRealVector(Doubles.toArray(targetValues));
    List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations,
            values -> targetVector
                    .getDistance(new ArrayRealVector(optimizerFunction.value(Doubles.toArray(values)))),
            progress -> progressListener.accept(0.5 * progress), exec);
    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    Result result = new Result();
    AtomicInteger count = new AtomicInteger(0);

    for (StartValues startValues : startValuesList) {
        if (exec != null) {
            exec.checkCanceled();
        }

        progressListener.accept(0.5 * count.get() / startValuesList.size() + 0.5);

        try {
            LeastSquaresBuilder builder = createLeastSquaresBuilder(startValues.getValues(), maxIterations);

            builder.checker((iteration, previous, current) -> {
                double currentProgress = (double) iteration / (double) maxIterations;

                if (exec != null) {
                    try {
                        exec.checkCanceled();
                    } catch (CanceledExecutionException e) {
                        return true;
                    }
                }

                progressListener.accept(0.5 * (count.get() + currentProgress) / startValuesList.size() + 0.5);
                return iteration == maxIterations;
            });

            LeastSquaresOptimizer.Optimum optimizerResults = optimizer.optimize(builder.build());

            if (exec != null) {
                exec.checkCanceled();
            }

            double cost = optimizerResults.getCost();

            if (result.sse == null || cost * cost < result.sse) {
                result = getResults(optimizerResults);

                if (result.sse == 0.0) {
                    break;
                }

                if (result.r2 != null && result.r2 > 0.0 && stopWhenSuccessful) {
                    break;
                }
            }
        } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) {
        }

        count.incrementAndGet();
    }

    return result;
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaBaseDispatcher.java

private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.failingOverRequest(outboundRequest.getURI().toString());
    URI uri;/*from  w w w  .  j a  v  a2 s  .  com*/
    String outboundURIs;
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }
    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
    outboundURIs = outboundRequest.getURI().toString();

    if (counter.incrementAndGet() <= maxFailoverAttempts) {
        //null out target url so that rewriters run again
        inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);

        uri = getUriFromInbound(inboundRequest, inboundResponse, outboundURIs);
        ((HttpRequestBase) outboundRequest).setURI(uri);
        if (failoverSleep > 0) {
            try {
                Thread.sleep(failoverSleep);
            } catch (InterruptedException e) {
                LOG.failoverSleepFailed(this.resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxFailoverAttemptsReached(maxFailoverAttempts, this.resourceRole);
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:eagle.jobrunning.crawler.RunningJobCrawlerImpl.java

private void startJobConfigProcessThread() {
    int configThreadCount = DEFAULT_CONFIG_THREAD_COUNT;
    LOG.info("Job Config crawler main thread started, pool size: " + DEFAULT_CONFIG_THREAD_COUNT);

    ThreadFactory factory = new ThreadFactory() {
        private final AtomicInteger count = new AtomicInteger(0);

        public Thread newThread(Runnable runnable) {
            count.incrementAndGet();//from  ww  w.  j  a va  2s.com
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
            thread.setName("config-crawler-workthread-" + count.get());
            return thread;
        }
    };

    ThreadPoolExecutor pool = new ThreadPoolExecutor(configThreadCount, configThreadCount, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), factory);

    while (true) {
        JobContext context;
        try {
            context = queueOfConfig.take();
            LOG.info("queueOfConfig size: " + queueOfConfig.size());
            Runnable configCrawlerThread = new ConfigWorkTask(new JobContext(context), fetcher, callback, this);
            pool.execute(configCrawlerThread);
        } catch (InterruptedException e) {
            LOG.warn("Got an InterruptedException: " + e.getMessage());
        } catch (RejectedExecutionException e2) {
            LOG.warn("Got RejectedExecutionException: " + e2.getMessage());
        } catch (Throwable t) {
            LOG.warn("Got an throwable t, " + t.getMessage());
        }
    }
}

From source file:com.google.android.gcm.server.AsyncSender.java

/**
 * Sends a message to one device, retrying in case of unavailability.
 *
 * <p>//from  w w w. j  av a2s. c o  m
 * <strong>Note: </strong> this method uses exponential back-off to retry in
 * case of service unavailability and hence could block the calling thread
 * for many seconds.
 *
 * @param message
 *            message to be sent, including the device's registration id.
 * @param to
 *            registration token, notification key, or topic where the
 *            message will be sent.
 * @param retries
 *            number of retries in case of service unavailability errors.
 *
 * @return result of the request (see its javadoc for more details).
 *
 * @throws IllegalArgumentException
 *             if to is {@literal null}.
 * @throws InvalidRequestException
 *             if GCM didn't returned a 200 or 5xx status.
 * @throws IOException
 *             if message could not be sent.
 */
public void send(Message message, String to, int retries, Callback<Result> callback) throws IOException {
    int attempt = 0;
    int backoff = BACKOFF_INITIAL_DELAY;

    // the wrapper callback for retrying scenario
    Callback<Result> sentCallBack = new Callback<Result>() {
        final AtomicInteger retryCounter = new AtomicInteger(0);

        @Override
        public void apply(Result result) {
            if (null == result) {
                if (retryCounter.incrementAndGet() <= retries) {
                    getLogger()
                            .debug("Attempt #" + attempt + " to send message " + message + " to regIds " + to);
                    try {
                        sleep(backoff / 2 + random.nextInt(backoff));
                        sendNoRetry(message, to, this);
                    } catch (IOException e) {
                        getLogger().error("Error while retrying to send message", e);
                        callback.apply(null);
                    }
                } else {
                    getLogger().warn("Max retrying times exceeded", new Exception());
                    callback.apply(null);
                }
            } else {
                callback.apply(result);
            }
        }
    };

    // try to send message for the first times...
    sendNoRetry(message, to, sentCallBack);
}