Example usage for java.util.concurrent ConcurrentLinkedQueue ConcurrentLinkedQueue

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

Introduction

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

Prototype

public ConcurrentLinkedQueue() 

Source Link

Document

Creates a ConcurrentLinkedQueue that is initially empty.

Usage

From source file:org.apache.zeppelin.socket.ConnectionManager.java

public void addUserConnection(String user, NotebookSocket conn) {
    LOGGER.debug("Add user connection {} for user: {}", conn, user);
    conn.setUser(user);/*from  ww  w .j  a  va2 s .c o m*/
    if (userSocketMap.containsKey(user)) {
        userSocketMap.get(user).add(conn);
    } else {
        Queue<NotebookSocket> socketQueue = new ConcurrentLinkedQueue<>();
        socketQueue.add(conn);
        userSocketMap.put(user, socketQueue);
    }
}

From source file:org.wso2.andes.kernel.disruptor.inbound.InboundTransactionEvent.java

/**
 * Transaction object to do a transaction
 * @param messagingEngine {@link org.wso2.andes.kernel.MessagingEngine}
 * @param eventManager InboundEventManager
 * @param maxBatchSize maximum batch size for a commit
 * @param channel AndesChannel//from  w  ww  .ja  va  2  s.  co  m
 * @param txWaitTimeout maximum wait time for commit, rollback or close event to complete
 */
public InboundTransactionEvent(MessagingEngine messagingEngine, InboundEventManager eventManager,
        int maxBatchSize, long txWaitTimeout, AndesChannel channel) {
    this.messagingEngine = messagingEngine;
    this.eventManager = eventManager;
    messageQueue = new ConcurrentLinkedQueue<>();
    taskCompleted = SettableFuture.create();
    this.maxBatchSize = maxBatchSize;
    this.channel = channel;
    this.txWaitTimeout = txWaitTimeout;
}

From source file:org.deeplearning4j.arbiter.optimize.candidategenerator.GridSearchCandidateGenerator.java

@Override
protected void initialize() {
    super.initialize();

    List<ParameterSpace> leaves = CollectionUtils.getUnique(parameterSpace.collectLeaves());
    int nParams = leaves.size();

    //Work out for each parameter: is it continuous or discrete?
    // for grid search: discrete values are grid-searchable as-is
    // continuous values: discretize using 'discretizationCount' bins
    // integer values: use min(max-min+1, discretizationCount) values. i.e., discretize if necessary
    numValuesPerParam = new int[nParams];
    long searchSize = 1;
    for (int i = 0; i < nParams; i++) {
        ParameterSpace ps = leaves.get(i);
        if (ps instanceof DiscreteParameterSpace) {
            DiscreteParameterSpace dps = (DiscreteParameterSpace) ps;
            numValuesPerParam[i] = dps.numValues();
        } else if (ps instanceof IntegerParameterSpace) {
            IntegerParameterSpace ips = (IntegerParameterSpace) ps;
            int min = ips.getMin();
            int max = ips.getMax();
            //Discretize, as some integer ranges are much too large to search (i.e., num. neural network units, between 100 and 1000)
            numValuesPerParam[i] = Math.min(max - min + 1, discretizationCount);
        } else {//from w  w w .j ava  2 s  .c om
            numValuesPerParam[i] = discretizationCount;
        }
        searchSize *= numValuesPerParam[i];
    }

    if (searchSize >= Integer.MAX_VALUE)
        throw new IllegalStateException(
                "Invalid search: cannot process search with " + searchSize + " candidates > Integer.MAX_VALUE"); //TODO find a more reasonable upper bound?

    order = new ConcurrentLinkedQueue<>();

    totalNumCandidates = (int) searchSize;
    switch (mode) {
    case Sequential:
        for (int i = 0; i < totalNumCandidates; i++) {
            order.add(i);
        }
        break;
    case RandomOrder:
        List<Integer> tempList = new ArrayList<>(totalNumCandidates);
        for (int i = 0; i < totalNumCandidates; i++) {
            tempList.add(i);
        }

        Collections.shuffle(tempList, new RandomAdaptor(rng));
        order.addAll(tempList);
        break;
    default:
        throw new RuntimeException();
    }

}

From source file:edu.mit.media.funf.probe.Probe.java

@Override
public final void onCreate() {
    Log.v(TAG, "CREATED");
    super.onCreate();
    enabled = false;//  www . ja  va2s.c o m
    running = false;
    pendingRequests = new ConcurrentLinkedQueue<Intent>();
    deadRequests = new ConcurrentLinkedQueue<Intent>();
}

From source file:org.apache.synapse.transport.passthru.DeliveryAgent.java

/**
 * This method queues the message for delivery. If a connection is already existing for
 * the destination epr, the message will be delivered immediately. Otherwise message has
 * to wait until a connection is established. In this case this method will inform the
 * system about the need for a connection.
 *
 * @param msgContext the message context to be sent
 * @param epr the endpoint to which the message should be sent
 * @throws AxisFault if an error occurs//from   w  w  w  .  j  av a  2  s .co m
 */
public void submit(MessageContext msgContext, EndpointReference epr) throws AxisFault {
    try {
        URL url = new URL(epr.getAddress());
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());

        HttpHost proxy = proxyConfig.selectProxy(target);
        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }

        // first we queue the message
        Queue<MessageContext> queue = null;
        lock.lock();
        try {
            queue = waitingMessages.get(route);
            if (queue == null) {
                queue = new ConcurrentLinkedQueue<MessageContext>();
                waitingMessages.put(route, queue);
            }
            if (queue.size() == maxWaitingMessages) {
                MessageContext msgCtx = queue.poll();

                targetErrorHandler.handleError(msgCtx, ErrorCodes.CONNECTION_TIMEOUT,
                        "Error connecting to the back end", null, ProtocolState.REQUEST_READY);
            }

            queue.add(msgContext);
        } finally {
            lock.unlock();
        }

        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            conn.resetInput();
            conn.resetOutput();
            MessageContext messageContext = queue.poll();

            if (messageContext != null) {
                tryNextMessage(messageContext, route, conn);
            }
        }

    } catch (MalformedURLException e) {
        handleException("Malformed URL in the target EPR", e);
    }
}

From source file:org.onehippo.cms7.brokenlinks.LinkChecker.java

private void runCheckerThreads(final Iterable<Link> links) {

    ConcurrentLinkedQueue<Link> queue = new ConcurrentLinkedQueue<Link>();

    for (Link link : links) {
        queue.add(link);//w ww.  j  a va  2  s.c om
    }

    final int threadCount = Math.min(queue.size(), nrOfThreads);
    final AtomicInteger internalLinksChecked = new AtomicInteger();

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; i++) {
        threads[i] = new LinkCheckerRunner(queue, internalLinksChecked);
        threads[i].setUncaughtExceptionHandler(new LogUncaughtExceptionHandler(log));
    }

    for (int i = 0; i < threadCount; i++) {
        threads[i].start();
    }

    try {
        for (int i = 0; i < threadCount; i++) {
            threads[i].join();
        }
    } catch (InterruptedException ex) {
        // aborted
    }

    try {
        session.refresh(false);
    } catch (RepositoryException e) {
        log.warn("Failed to clear the session.", e);
    }
}

From source file:com.thoughtworks.go.server.service.dd.DependencyFanInNode.java

private Pair<StageIdentifier, List<FaninScmMaterial>> getRevisionNthFor(int n, FanInGraphContext context) {
    List<FaninScmMaterial> scmMaterials = new ArrayList<>();
    PipelineTimeline pipelineTimeline = context.pipelineTimeline;
    Queue<PipelineTimelineEntry.Revision> revisionQueue = new ConcurrentLinkedQueue<>();
    DependencyMaterialConfig dependencyMaterial = (DependencyMaterialConfig) materialConfig;
    PipelineTimelineEntry entry = pipelineTimeline.instanceFor(dependencyMaterial.getPipelineName(),
            totalInstanceCount - n);/*from w  w w.  j  ava  2 s . c  o m*/

    Set<CaseInsensitiveString> visitedNodes = new HashSet<>();

    StageIdentifier dependentStageIdentifier = dependentStageIdentifier(context, entry,
            CaseInsensitiveString.str(dependencyMaterial.getStageName()));
    if (!StageIdentifier.NULL.equals(dependentStageIdentifier)) {
        addToRevisionQueue(entry, revisionQueue, scmMaterials, context, visitedNodes);
    } else {
        return null;
    }
    while (!revisionQueue.isEmpty()) {
        PipelineTimelineEntry.Revision revision = revisionQueue.poll();
        DependencyMaterialRevision dmr = DependencyMaterialRevision.create(revision.revision, null);
        PipelineTimelineEntry pte = pipelineTimeline
                .getEntryFor(new CaseInsensitiveString(dmr.getPipelineName()), dmr.getPipelineCounter());
        addToRevisionQueue(pte, revisionQueue, scmMaterials, context, visitedNodes);
    }

    return new Pair<>(dependentStageIdentifier, scmMaterials);
}

From source file:org.jasig.portal.io.xml.PortalDataKeyFileProcessor.java

@Override
public Object apply(Resource input) {
    final InputStream fis;
    try {/*from   w w w.  j a va2s.  com*/
        fis = input.getInputStream();
    } catch (IOException e) {
        if (this.options == null || this.options.isFailOnError()) {
            throw new RuntimeException("Failed to create InputStream for: " + input, e);
        }

        logger.warn("Failed to create InputStream, resource will be ignored: {}", input);
        return null;
    }

    final PortalDataKey portalDataKey;
    final BufferedXMLEventReader xmlEventReader;
    try {
        xmlEventReader = new BufferedXMLEventReader(this.xmlInputFactory.createXMLEventReader(fis), -1);

        final StartElement rootElement = StaxUtils.getRootElement(xmlEventReader);
        portalDataKey = new PortalDataKey(rootElement);
    } catch (Exception e) {
        if (this.options != null && !this.options.isIngoreNonDataFiles()) {
            throw new RuntimeException("Failed to parse: " + input, e);
        }

        logger.warn("Failed to parse resource, it will be ignored: {}", input);
        return null;
    } finally {
        IOUtils.closeQuietly(fis);
    }
    xmlEventReader.reset();

    final IPortalDataType portalDataType = this.dataKeyTypes.get(portalDataKey);
    if (portalDataType == null) {
        logger.warn("No IPortalDataType configured for {}, the resource will be ignored: {}", portalDataKey,
                input);
        return null;
    }

    //Allow the PortalDataType to do any necessary post-processing of the input, needed as some types require extra work
    final String resourceUri = ResourceUtils.getResourceUri(input);
    final Set<PortalDataKey> processedPortalDataKeys = portalDataType.postProcessPortalDataKey(resourceUri,
            portalDataKey, xmlEventReader);
    xmlEventReader.reset();

    for (final PortalDataKey processedPortalDataKey : processedPortalDataKeys) {
        //Add the PortalDataKey and File into the map
        Queue<Resource> queue = this.dataToImport.get(processedPortalDataKey);
        if (queue == null) {
            queue = ConcurrentMapUtils.putIfAbsent(this.dataToImport, processedPortalDataKey,
                    new ConcurrentLinkedQueue<Resource>());
        }
        queue.offer(input);
        count.incrementAndGet();
    }

    return null;
}

From source file:com.github.wolfdogs.kemono.util.event.RootEventManager.java

private HandlerEntry addHandlerEntry(HandlerEntry entry) {
    Class<? extends Event> type = entry.getType();
    Object relatedObject = entry.getRelatedObject();

    Map<Object, Queue<HandlerEntry>> objectEntriesMap = handlerEntryContainersMap.get(type);
    if (objectEntriesMap == null) {
        objectEntriesMap = new ConcurrentHashMap<Object, Queue<HandlerEntry>>();
        handlerEntryContainersMap.put(type, objectEntriesMap);
    }/*  w  w  w . java2  s .co m*/

    Queue<HandlerEntry> entries = objectEntriesMap.get(relatedObject);
    if (entries == null) {
        entries = new ConcurrentLinkedQueue<HandlerEntry>();
        objectEntriesMap.put(relatedObject, entries);
    }

    entries.add(entry);
    return entry;
}

From source file:io.hops.ha.common.RMNodeInfo.java

public void toAddNodeUpdateQueue(
        org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo uci) {
    if (this.nodeUpdateQueueToAdd == null) {
        this.nodeUpdateQueueToAdd = new ConcurrentLinkedQueue<org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo>();
    }/*from w  w w  .  j a v  a 2s.c o m*/
    this.nodeUpdateQueueToAdd.add(uci);
}