Example usage for java.util.concurrent CyclicBarrier getNumberWaiting

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

Introduction

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

Prototype

public int getNumberWaiting() 

Source Link

Document

Returns the number of parties currently waiting at the barrier.

Usage

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  a v a  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;
}