Example usage for java.util.concurrent ConcurrentLinkedQueue remove

List of usage examples for java.util.concurrent ConcurrentLinkedQueue remove

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentLinkedQueue remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes a single instance of the specified element from this queue, if it is present.

Usage

From source file:com.clican.pluto.cluster.base.BaseMessageDispatcher.java

public synchronized void unbind(String msgName, IMessageHandler handler) {
    if (StringUtils.isEmpty(msgName) || handler == null) {
        throw new IllegalArgumentException("The message name and message handler can't be null");
    }/*from   w w  w .ja  va 2s  .  co  m*/
    ConcurrentLinkedQueue<IMessageHandler> handlerQueue = messageHandlerMapping.get(msgName);
    if (handlerQueue == null || !handlerQueue.contains(handler)) {
        log.warn("The message handler [" + handler + "] is not binded by [" + msgName + "]");
    }
    handlerQueue.remove(handler);
}

From source file:de.da_sense.moses.client.service.MosesService.java

/**
 * Checks all hooks with type == hookType for the one containing the Executor executable. 
 * If found it removes this hook.// w w w. j  av a2  s . c  o m
 * @param hookType The type of Hook to unregister
 * @param executable The Executer to unregister
 */
public void unregisterHook(HookTypesEnum hookType, Executable executable) {
    ConcurrentLinkedQueue<ExecutableWithType> hook = getHook(hookType);
    ExecutableWithType exeCutableWithTypeCurrent = null;
    for (ExecutableWithType executableWithType : hook) {
        if (executableWithType.e.equals(executable)) {
            exeCutableWithTypeCurrent = executableWithType;
            break;
        }
    }
    if (exeCutableWithTypeCurrent != null)
        hook.remove(exeCutableWithTypeCurrent);
}

From source file:dendroscope.autumn.hybridnumber.ComputeHybridNumber.java

/**
 * recursively compute the hybrid number
 *
 * @param root1/*from   w w w  .  j  a  v  a  2s  .com*/
 * @param root2
 * @param isReduced       @return hybrid number
 * @param retry
 * @param topLevel
 * @param scoreAbove
 * @param additionalAbove
 */
private int computeHybridNumberRec(final Root root1, final Root root2, boolean isReduced,
        Integer previousHybrid, BitSet retry, final boolean topLevel, final int scoreAbove,
        final ValuesList additionalAbove) throws IOException, CanceledException {
    if (System.currentTimeMillis() > nextTime) {
        synchronized (progressListener) {
            nextTime += waitTime;
            waitTime *= 1.5;
            progressListener.incrementProgress();
        }
    } else
        progressListener.checkForCancel();

    // System.err.println("computeHybridNumberRec: tree1=" + Basic.toString(root1.getTaxa()) + " tree2=" + Basic.toString(root2.getTaxa()));
    // root1.reorderSubTree();
    //  root2.reorderSubTree();
    if (checking) {
        root1.checkTree();
        root2.checkTree();
    }

    BitSet taxa = root1.getTaxa();

    String key = root1.toStringTreeSparse() + root2.toStringTreeSparse();
    // System.err.println("Key: "+key);
    Integer value;
    synchronized (lookupTable) {
        value = (Integer) lookupTable.get(key);
        if (value != null)
            return value;
    }

    if (!root2.getTaxa().equals(taxa))
        throw new RuntimeException("Unequal taxon sets: X=" + Basic.toString(root1.getTaxa()) + " vs "
                + Basic.toString(root2.getTaxa()));
    if (!isReduced) {
        switch (SubtreeReduction.apply(root1, root2, null)) {
        case ISOMORPHIC:
            synchronized (lookupTable) {
                lookupTable.put(key, 0);
            }
            if (topLevel) {
                bestScore.lowerTo(0);
                progressListener.setSubtask("Best score: " + bestScore);
            }
            return 0; // two trees are isomorphic, no hybrid node needed
        case REDUCED: // a reduction was performed, cannot maintain lexicographical ordering in removal loop below
            previousHybrid = null;
            break;
        case IRREDUCIBLE:
            break;
        }

        Single<Integer> placeHolderTaxa = new Single<Integer>();
        final Pair<Root, Root> clusterTrees = ClusterReduction.apply(root1, root2, placeHolderTaxa);
        final boolean retryTop = false && (previousHybrid != null && placeHolderTaxa.get() < previousHybrid);
        // if the taxa involved in the cluster reduction come before the previously removed hybrid, do full retry
        // retryTop doesn't work
        final BitSet fRetry = retry;

        if (clusterTrees != null) // will perform cluster-reduction
        {
            final Value score1 = new Value(0);
            final Value score2 = new Value(1); // because the cluster could not be reduced using an subtree reduction, can assume that we will need one reticulation for this

            final boolean verbose = ProgramProperties.get("verbose-HL-parallel", false);
            if (verbose)
                System.err.println("Starting parallel loop");

            final CountDownLatch countDownLatch = new CountDownLatch(2);
            final Integer fPrevious = previousHybrid;

            // setup task:
            final Task task1 = new Task(); // first of two cluster-reduction tasks
            task1.setRunnable(new Runnable() {
                public void run() {
                    try {
                        if (verbose) {
                            System.err.println("Launching thread on cluster-reduction");
                            System.err
                                    .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount());
                        }
                        final ValuesList additionalAbove1 = additionalAbove.copyWithAdditionalElement(score2);
                        if (scoreAbove + additionalAbove1.sum() < bestScore.get()) {
                            int h = computeHybridNumberRec(root1, root2, false, fPrevious, fRetry, false,
                                    scoreAbove, additionalAbove1);
                            score1.set(h);
                        } else {
                            score1.set(LARGE);
                        }
                        additionalAbove1.clear();
                    } catch (Exception ex) {
                        while (countDownLatch.getCount() > 0)
                            countDownLatch.countDown();
                    }
                    countDownLatch.countDown();
                }
            });

            final Task task2 = new Task(); // second of two cluster-reduction tasks
            task2.setRunnable(new Runnable() {
                public void run() {
                    try {
                        if (verbose) {
                            System.err.println("Launching thread on cluster-reduction");
                            System.err
                                    .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount());
                        }
                        final ValuesList additionalAbove2 = additionalAbove.copyWithAdditionalElement(score1);
                        if (scoreAbove + additionalAbove2.sum() < bestScore.get()) {
                            int h = computeHybridNumberRec(clusterTrees.getFirst(), clusterTrees.getSecond(),
                                    true, fPrevious, fRetry, false, scoreAbove, additionalAbove2);
                            score2.set(h);
                        } else {
                            score2.set(LARGE);
                        }
                        additionalAbove2.clear();
                    } catch (Exception ex) {
                        while (countDownLatch.getCount() > 0)
                            countDownLatch.countDown();
                    }
                    countDownLatch.countDown();
                }
            });

            // start a task in this thread
            scheduledThreadPoolExecutor.execute(task1);
            task2.run();
            task1.run(); // try to run task1 in current thread if it hasn't yet started execution. If the task is already running or has completed, will simply return

            try {
                if (verbose)
                    System.err.println("waiting...");
                // wait until all tasks have completed
                countDownLatch.await();
                if (verbose)
                    System.err.println("done");
            } catch (InterruptedException e) {
                Basic.caught(e);
            }

            clusterTrees.getFirst().deleteSubTree();
            clusterTrees.getSecond().deleteSubTree();

            int total = scoreAbove + additionalAbove.sum() + score1.get() + score2.get();

            if (topLevel && (total < bestScore.get())) // score above will be zero, but put this here anyway to avoid confusion
            {
                bestScore.lowerTo(total);
                progressListener.setSubtask("Current best score: " + bestScore);
            }

            synchronized (lookupTable) {
                Integer old = (Integer) lookupTable.get(key);
                if (old == null || total < old)
                    lookupTable.put(key, total);
            }
            return score1.get() + score2.get();
        }
    }

    List<Root> leaves1 = root1.getAllLeaves();

    if (leaves1.size() <= 2) // try 2 rather than one...
    {
        return 0;
    }

    final boolean verbose = ProgramProperties.get("verbose-HL-parallel", false);
    if (verbose)
        System.err.println("Starting parallel loop");

    final CountDownLatch countDownLatch = new CountDownLatch(leaves1.size());

    final Value bestSubH = new Value(LARGE);

    // schedule all tasks to be performed
    final ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<Task>();

    for (Node leaf2remove : leaves1) {
        final BitSet taxa2remove = ((Root) leaf2remove).getTaxa();

        if (previousHybrid == null || previousHybrid < taxa2remove.nextSetBit(0)) {

            if (scoreAbove + additionalAbove.sum() + 1 >= bestScore.get())
                return LARGE; // other thread has found a better result, abort

            // setup task:
            final Task task = new Task();
            task.setRunnable(new Runnable() {
                public void run() {
                    try {
                        if (verbose) {
                            System.err.println("Launching thread on " + Basic.toString(taxa2remove));
                            System.err
                                    .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount());
                        }
                        queue.remove(task);
                        if (scoreAbove + additionalAbove.sum() + 1 < bestScore.get()) {
                            Root tree1X = CopyWithTaxaRemoved.apply(root1, taxa2remove);
                            Root tree2X = CopyWithTaxaRemoved.apply(root2, taxa2remove);

                            Refine.apply(tree1X, tree2X);

                            int scoreBelow = computeHybridNumberRec(tree1X, tree2X, false,
                                    taxa2remove.nextSetBit(0), null, false, scoreAbove + 1, additionalAbove)
                                    + 1;

                            if (topLevel && scoreBelow < bestScore.get()) {
                                bestScore.lowerTo(scoreBelow);
                                progressListener.setSubtask("Current best score: " + bestScore);
                            }

                            synchronized (bestSubH) {
                                if (scoreBelow < bestSubH.get())
                                    bestSubH.set(scoreBelow);
                            }

                            tree1X.deleteSubTree();
                            tree2X.deleteSubTree();
                        }
                    } catch (Exception ex) {
                        while (countDownLatch.getCount() > 0)
                            countDownLatch.countDown();
                    }
                    countDownLatch.countDown();
                }
            });
            queue.add(task);
        } else // no task for this item, count down
        {
            countDownLatch.countDown();
            progressListener.checkForCancel();
        }
    }
    // grab one task for the current thread:
    Task taskForCurrentThread = queue.size() > 0 ? queue.poll() : null;
    // launch all others in the executor
    for (Task task : queue)
        scheduledThreadPoolExecutor.execute(task);

    // start a task in this thread
    if (taskForCurrentThread != null)
        taskForCurrentThread.run();

    // try to run other tasks from the queue. Note that any task that is already running will return immediately
    while (queue.size() > 0) {
        Task task = queue.poll();
        if (task != null)
            task.run();
    }
    try {
        if (verbose)
            System.err.println("waiting...");
        // wait until all tasks have completed
        countDownLatch.await();

        if (verbose)
            System.err.println("done");
    } catch (InterruptedException e) {
        Basic.caught(e);
        return LARGE;
    }
    // return the best value
    synchronized (lookupTable) {
        Integer old = (Integer) lookupTable.get(key);
        if (old == null || old > bestSubH.get())
            lookupTable.put(key, bestSubH.get());
    }
    return bestSubH.get();
}

From source file:server.Folder.java

/**
 * Copy all versions of the objects found in a folder. This will create the complete object tree of
 * the objects, so if an object has ancestors or descendants in other folders, those will be copied, too.
 * @param folderContent the content of the folder which should be copied completely.
 * @param otc a ObjectTreeCopier which is configured with a validator and correct activeUser.
 * @param croakOnError if true, stop in case of an error and return a CopyResult which contains the events so far.
 * @return a copyResult containing a collection of all failed and successful attempts at copying the
 * folder's contents.//from w w  w . ja  va 2s  .co  m
 */
CopyResult copyAllVersions(Collection<ObjectSystemData> folderContent, ObjectTreeCopier otc,
        Boolean croakOnError) {
    ObjectSystemDataDAO oDao = daoFactory.getObjectSystemDataDAO(HibernateSession.getLocalEntityManager());
    CopyResult copyResult = new CopyResult();

    ConcurrentLinkedQueue<ObjectSystemData> conQueue = new ConcurrentLinkedQueue<ObjectSystemData>();
    conQueue.addAll(folderContent);
    log.debug("starting to copy " + conQueue.size() + " objects");

    for (ObjectSystemData source : conQueue) {
        //            otc.resetCopyResult();
        try {
            // create a full copy of the whole object tree:
            otc.createFullCopy(source);
            copyResult.addCopyResult(otc.getCopyResult());
        } catch (Exception ex) {
            log.debug("objectTreeCopy failed for id " + source.getId(), ex);
            // copy failed - now we have to cleanup and remove the already created copies:
            ObjectSystemData brokenCopy = otc.getCopyCache().get(source);
            if (brokenCopy != null) {
                // we should nuke all other objects with the same root,
                // as they won't be amendable to a copy operation either.
                for (ObjectSystemData osd : conQueue) {
                    if (osd.getRoot().equals(brokenCopy.getRoot())) {
                        conQueue.remove(osd);
                    }
                }

                // recursively delete the broken object tree.
                oDao.delete(brokenCopy.getRoot(), true, true);
            }

            log.debug("cleanup complete.");
            copyResult.addFailure(source, new CinnamonException(ex));
            if (croakOnError) {
                return copyResult;
            }
        }
    }
    return copyResult;
}