Example usage for java.util.concurrent CyclicBarrier reset

List of usage examples for java.util.concurrent CyclicBarrier reset

Introduction

In this page you can find the example usage for java.util.concurrent CyclicBarrier reset.

Prototype

public void reset() 

Source Link

Document

Resets the barrier to its initial state.

Usage

From source file:com.adaptris.core.interceptor.ThrottlingInterceptor.java

private boolean throttle(final long delay) {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    // This is to make sure we don't break the barrier before the real delay is up.
    // /*from  ww  w  .  jav a 2  s  . c o m*/
    long barrierDelay = delay + TimeUnit.SECONDS.toMillis(1L);
    boolean result = true;
    try {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(delay);
                    barrier.await(TimeUnit.SECONDS.toMillis(1L), TimeUnit.MILLISECONDS);
                } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
                    log.trace("Interrupted during sleep; breaking barrier");
                    barrier.reset();
                }
            }

        });
        barrier.await(barrierDelay, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
        result = false;
    }
    return result;
}

From source file:com.adaptris.core.PoolingWorkflow.java

private void populatePool() throws CoreException {
    int size = minIdle();
    ExecutorService populator = Executors.newCachedThreadPool();
    try {// w w w .  j  a  v  a2  s  .co m
        final CyclicBarrier barrier = new CyclicBarrier(size + 1);
        log.trace("Need more ({}) children as soon as possible to handle work. Get to it", size);
        final List<Worker> workers = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            populator.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Worker w = objectPool.borrowObject();
                        workers.add(w);
                        barrier.await(initWaitTimeMs(), TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        barrier.reset();
                    }
                }
            });
        }
        barrier.await(initWaitTimeMs(), TimeUnit.MILLISECONDS);
        for (Worker worker : workers) {
            objectPool.returnObject(worker);
        }
    } catch (Exception e) {
        throw new CoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:com.bt.aloha.batchtest.BatchTest.java

public void run(String scenarioName) {
    this.numberCompleted = 0;
    this.numberSucceeded = 0;
    this.results = new ConcurrentHashMap<String, Result>();
    normalizeWeightings();//from  w  ww . j a  v  a 2s.  co m
    totalTime = 0;
    CyclicBarrier barrier = new CyclicBarrier(numberOfConcurrentStarts);
    for (int i = 0; i < numberOfRuns; i++) {
        try {
            if (manager != null)
                manager.doApplicationContextStartStop();
            long startTime = System.currentTimeMillis();
            Thread.sleep(1000);
            String[] beans = new String[numberOfConcurrentStarts];
            BatchTestScenario[] concurrentScenarios = new BatchTestScenario[numberOfConcurrentStarts];
            for (int j = 0; j < numberOfConcurrentStarts; j++) {
                beans[j] = scenarioName == null ? pickScenarioName() : scenarioName;

                BatchTestScenario s = (BatchTestScenario) applicationContext.getBean(beans[j]);
                ((BatchTestScenarioBase) s).setCallCollection(callCollection);
                ((BatchTestScenarioBase) s).setAudioFileUri(audioFileUri);

                if (s.getBatchTestScenarioResultListener() == null)
                    s.setBatchTestScenarioResultListener(this);
                concurrentScenarios[j] = s;
            }

            CountDownLatch latch = new CountDownLatch(numberOfConcurrentStarts);
            for (int j = 0; j < numberOfConcurrentStarts; j++) {
                if (concurrentScenarios[j] == null)
                    break;
                RunScenario rs = new RunScenario(concurrentScenarios[j], beans[j], barrier, latch);
                executorService.execute(rs);
            }
            latch.await();
            barrier.reset();
            totalTime += System.currentTimeMillis() - startTime;
        } catch (Throwable t) {
            log.error(String.format("Test run %d threw an exception", i), t);
        }
    }

    waitForAllToFinish(maximumScenarioCompletionWaitTimeSeconds);
    log.info("Finishing...");
    if (results.size() < 1) {
        log.info("NO scenarios run!");
        return;
    }
    numberSucceeded = 0;
    for (String o : results.keySet()) {
        String scenario = o.split(":")[0];
        Result res = results.get(o);
        Analysis result = analysis.get(scenario);
        if (result != null) {
            if (res.isSucceeded()) {
                result.setSuccessCount(result.getSuccessCount() + 1);
            } else {
                result.setFailureCount(result.getFailureCount() + 1);
            }
            log.info(String.format("Scenario %s %s", o, res.toString()));
            System.err.println(String.format("Scenario %s %s", o, res.toString()));
            numberCompleted++;
            if (res.isSucceeded())
                numberSucceeded++;
            else
                failedScenarios.add(o);
        } else {
            log.error("unable to find result for scenario " + scenario);
        }
    }
    log.info(numberSucceeded + " successful scenarios, " + successRate() + "% passed");
    log.info(numberCompleted());
    if (manager != null) {
        log.info("Access to ApplicationContext1 #: " + manager.getCountReturnedAppCtx1());
        log.info("Access to ApplicationContext2 #: " + manager.getCountReturnedAppCtx2());
    }
    resetDb();
}

From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java

public static boolean submitParallelTasks(final ApplicationThreadManager threadManager, final UITask parent,
        UITask... children) {/*from  w  w  w  .j  ava  2 s  .c om*/
    final AtomicInteger childSuccesses = new AtomicInteger(0);
    final AtomicInteger childFailures = new AtomicInteger(0);

    if (parent == null) {
        throw new IllegalArgumentException("parent task cannot be NULL");
    }

    if (ArrayUtils.isEmpty(children)) {
        throw new IllegalArgumentException("Need to provide at least one child task");
    }
    final CyclicBarrier startBarrier = new CyclicBarrier(children.length + 1) {
        @Override
        public void reset() {
            System.out.println("========== resetting start barrier =========== ");
            super.reset();
        }
    };

    final CountDownLatch childrenTerminated = new CountDownLatch(children.length);

    int submittedChildren = 0;
    for (final UITask child : children) {

        final UITask wrapped = new UITask() {

            @Override
            public void successHook() throws Exception {
                boolean success = false;
                try {
                    child.successHook();
                    success = true;
                } finally {
                    if (success) {
                        childSuccesses.incrementAndGet();
                    } else {
                        childFailures.incrementAndGet();
                    }
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void beforeExecution() {
                child.beforeExecution();
                // note: when this method throws an exception , #failure() is invoked
            }

            @Override
            public void setEnabledHook(boolean yesNo) {
                child.setEnabledHook(yesNo);

            }

            @Override
            public void failureHook(Throwable t) throws Exception {
                try {
                    child.failureHook(t);
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public void cancellationHook() {
                try {
                    child.cancellationHook();
                } finally {
                    childFailures.incrementAndGet();
                    childrenTerminated.countDown();
                }
            }

            @Override
            public String getId() {
                return child.getId();
            }

            @Override
            public void run() throws Exception {
                try {
                    if (log.isTraceEnabled()) {
                        log.trace("run(): Child task " + getId() + " is now waiting.");
                    }
                    startBarrier.await(); // will BrokenBarrierException if any of the child tasks could not be started,
                } catch (InterruptedException e) {
                    log.error("run(): Child task " + getId() + " was interrupted");
                    Thread.currentThread().interrupt();
                } catch (BrokenBarrierException e) {
                    log.error("run(): Child task" + getId() + " aborted, barrier broken.");
                    throw new RuntimeException(
                            "Child task not started because another child task failed submitTask()");
                }

                if (log.isTraceEnabled()) {
                    log.trace("run(): Child task " + getId() + " is now running.");
                }
                child.run();
            }
        };

        if (null == threadManager.submitTask(wrapped, false)) {
            log.error("submitParallelTasks(): Failed to submit child " + child);

            // note: I wait for (submittedChildren-childFailures) because some 
            // child task may have already failed before reaching their run() method
            while (startBarrier.getNumberWaiting() != (submittedChildren - childFailures.get())) {
                log.info("submitParallelTasks(): Waiting for all child tasks to reach barrier ( "
                        + startBarrier.getNumberWaiting() + " waiting)");
                try {
                    java.lang.Thread.sleep(500);
                } catch (Exception e) {
                }
                ;
            }

            startBarrier.reset(); // will cause all child threads waiting on this barrier to terminate
            return false;
        }
        submittedChildren++;
    }

    /*
     * All children are submitted and waiting at the barrier.
     */
    final boolean parentSubmitted = null != threadManager.submitTask("Control thread of " + parent.getId(),
            new Runnable() {

                @Override
                public void run() {
                    try {

                        while (true) {
                            try {
                                log.debug("run(): Parent task " + parent.getId()
                                        + " is waiting for it's children to start...");
                                startBarrier.await(5, TimeUnit.SECONDS);
                                break;
                            } catch (TimeoutException e) {
                                if (childFailures.get() != 0) {
                                    runFailureHookOnEDT(parent,
                                            childFailures.get() + " child tasks of parent task "
                                                    + parent.getId() + " failed to start.");
                                    return;
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting" + " for it's children to start.");
                        startBarrier.reset(); // let children fail.
                        Thread.currentThread().interrupt();
                        return;
                    } catch (BrokenBarrierException e) {
                        runFailureHookOnEDT(parent,
                                "Parent task " + parent.getId() + " failed to wait for it's children");
                        throw new RuntimeException("Internal error - task " + parent.getId()
                                + " failed to wait for it's children?");
                    }

                    log.debug("run(): Task " + parent.getId() + " is waiting for it's children to finish");
                    try {
                        childrenTerminated.await();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        runFailureHookOnEDT(parent, "Parent task " + parent.getId()
                                + " was interrupted while waiting for it's children");
                        return;
                    }

                    log.info("run(): All children of parent task " + parent.getId()
                            + " have finished ( success: " + childSuccesses.get() + " / failure: "
                            + childFailures.get() + ")");

                    if (childFailures.get() > 0) {
                        runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent "
                                + parent.getId() + " have FAILED.");
                        return;
                    }

                    if (null == threadManager.submitTask(parent, false)) {
                        runFailureHookOnEDT(parent, "Failed to submit parent task " + parent.getId());
                        return;
                    }

                }
            }, false);

    if (!parentSubmitted) {
        log.debug("submitParallelTasks(): Failed to submit parent task " + parent.getId()
                + " , terminating child tasks.");
        startBarrier.reset(); // aborts all child tasks with a BrokenBarrierException
    }

    return parentSubmitted;
}

From source file:org.acmsl.queryj.api.handlers.AbstractTemplateWritingHandler.java

/**
 * Writes the templates./*from  w w w.ja va2  s . c  o  m*/
 * @param templates the templates.
 * @param engineName the engine name.
 * @param parameters the parameters.
 * @param charset the file encoding.
 * @param templateGenerator the template generator.
 * @param threadCount the number of threads to use.
 * @param rootDir the root dir.
 * @return the futures for the concurrent threads.
 * @throws QueryJBuildException if the templates cannot be written.
 */
@NotNull
@SuppressWarnings("unused")
protected List<Future<?>> writeTemplatesMultithread2ndVersion(@Nullable final List<T> templates,
        @NotNull final String engineName, @NotNull final QueryJCommand parameters,
        @NotNull final Charset charset, @NotNull final TG templateGenerator, final int threadCount,
        @NotNull final File rootDir) throws QueryJBuildException {
    @NotNull
    final List<Future<?>> result;

    if (templates != null) {
        result = new ArrayList<>(templates.size());

        @NotNull
        final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);

        @NotNull
        final CyclicBarrier round = new CyclicBarrier(threadCount);

        @NotNull
        AtomicInteger index = new AtomicInteger(0);

        int intIndex;

        @Nullable
        final Log t_Log = UniqueLogFactory.getLog(AbstractTemplateWritingHandler.class);

        for (@Nullable
        final T t_Template : templates) {
            if (t_Template != null) {
                intIndex = index.incrementAndGet();

                if (intIndex <= threadCount) {
                    if (t_Log != null) {
                        t_Log.info("Starting a new thread " + intIndex + "/" + threadCount);
                    }

                    result.add(threadPool.submit((Runnable) buildGeneratorThread(t_Template, templateGenerator,
                            retrieveOutputDir(t_Template.getTemplateContext(), rootDir, parameters), rootDir,
                            charset, intIndex, round, parameters)));
                } else {
                    if (t_Log != null) {
                        t_Log.info("No threads available " + intIndex + "/" + threadCount);
                    }

                    index = new AtomicInteger(0);

                    try {
                        round.await();
                    } catch (@NotNull final InterruptedException interrupted) {
                        if (t_Log != null) {
                            t_Log.info("Thread pool interrupted while waiting", interrupted);
                        }
                    } catch (@NotNull final BrokenBarrierException brokenBarrier) {
                        if (t_Log != null) {
                            t_Log.info(BROKEN_BARRIER_LITERAL, brokenBarrier);
                        }
                    }

                    if (t_Log != null) {
                        t_Log.info("Resetting thread pool (shutdown? " + threadPool.isShutdown() + ")");
                    }

                    round.reset();
                }
            }
        }
    } else {
        result = new ArrayList<>(0);
    }

    return result;
}