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:com.chinamobile.bcbsp.comm.CommunicatorNew.java

@Override
public ConcurrentLinkedQueue<IMessage> getMessageQueue(String vertexID) throws IOException {
    ArrayList<IMessage> tmpList = messageManager.removeIncomedQueue(vertexID);
    // Note Singleton
    if (tmpList == null) {
        return singletonMsg;
    }//from w w w  .j a  v  a2 s  .c  o m
    ConcurrentLinkedQueue<IMessage> tmpQueue = new ConcurrentLinkedQueue<IMessage>();
    while (!tmpList.isEmpty()) {
        tmpQueue.add(tmpList.remove(0));
    }
    tmpList = null;
    return tmpQueue;
}

From source file:net.dv8tion.jda.audio.AudioConnection.java

private void setupReceiveThread() {
    if (receiveHandler != null && udpSocket != null) {
        if (receiveThread == null) {
            receiveThread = new Thread("AudioConnection ReceiveThread Guild: " + channel.getGuild().getId()) {
                @Override/*from w  w w. j  a  v a2  s  . c om*/
                public void run() {
                    try {
                        udpSocket.setSoTimeout(100);
                    } catch (SocketException e) {
                        LOG.log(e);
                    }
                    while (!udpSocket.isClosed() && !this.isInterrupted()) {
                        DatagramPacket receivedPacket = new DatagramPacket(new byte[1920], 1920);
                        try {
                            udpSocket.receive(receivedPacket);

                            if (receiveHandler != null
                                    && (receiveHandler.canReceiveUser() || receiveHandler.canReceiveCombined())
                                    && webSocket.getSecretKey() != null) {
                                if (!couldReceive) {
                                    couldReceive = true;
                                    sendSilentPackets();
                                }
                                AudioPacket decryptedPacket = AudioPacket.decryptAudioPacket(receivedPacket,
                                        webSocket.getSecretKey());

                                String userId = ssrcMap.get(decryptedPacket.getSSRC());
                                Decoder decoder = opusDecoders.get(decryptedPacket.getSSRC());
                                if (userId == null) {
                                    byte[] audio = decryptedPacket.getEncodedAudio();
                                    if (!Arrays.equals(audio, silenceBytes))
                                        LOG.debug("Received audio data with an unknown SSRC id.");
                                } else if (decoder == null)
                                    LOG.warn(
                                            "Received audio data with known SSRC, but opus decoder for this SSRC was null. uh..HOW?!");
                                else if (!decoder.isInOrder(decryptedPacket.getSequence()))
                                    LOG.trace("Got out-of-order audio packet. Ignoring.");
                                else {
                                    User user = getJDA().getUserById(userId);
                                    if (user == null)
                                        LOG.warn(
                                                "Received audio data with a known SSRC, but the userId associate with the SSRC is unknown to JDA!");
                                    else {
                                        //                                            if (decoder.wasPacketLost(decryptedPacket.getSequence()))
                                        //                                            {
                                        //                                                LOG.debug("Packet(s) missed. Using Opus packetloss-compensation.");
                                        //                                                short[] decodedAudio = decoder.decodeFromOpus(null);
                                        //                                                receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio));
                                        //                                            }
                                        short[] decodedAudio = decoder.decodeFromOpus(decryptedPacket);

                                        //If decodedAudio is null, then the Opus decode failed, so throw away the packet.
                                        if (decodedAudio == null) {
                                            LOG.trace(
                                                    "Received audio data but Opus failed to properly decode, instead it returned an error");
                                        } else {
                                            if (receiveHandler.canReceiveUser()) {
                                                receiveHandler
                                                        .handleUserAudio(new UserAudio(user, decodedAudio));
                                            }
                                            if (receiveHandler.canReceiveCombined()) {
                                                Queue<Pair<Long, short[]>> queue = combinedQueue.get(user);
                                                if (queue == null) {
                                                    queue = new ConcurrentLinkedQueue<>();
                                                    combinedQueue.put(user, queue);
                                                }
                                                queue.add(Pair.<Long, short[]>of(System.currentTimeMillis(),
                                                        decodedAudio));
                                            }
                                        }
                                    }
                                }
                            } else if (couldReceive) {
                                couldReceive = false;
                                sendSilentPackets();
                            }
                        } catch (SocketTimeoutException e) {
                            //Ignore. We set a low timeout so that we wont block forever so we can properly shutdown the loop.
                        } catch (SocketException e) {
                            //The socket was closed while we were listening for the next packet.
                            //This is expected. Ignore the exception. The thread will exit during the next while
                            // iteration because the udpSocket.isClosed() will return true.
                        } catch (Exception e) {
                            LOG.log(e);
                        }
                    }
                }
            };
            receiveThread.setDaemon(true);
            receiveThread.start();
        }
        if (receiveHandler.canReceiveCombined()) {
            setupCombinedExecutor();
        }
    }
}

From source file:com.xeiam.xchange.streaming.socketio.IOConnection.java

/**
 * Transport connected. {@link IOTransport} calls this when a connection is established.
 *//*  w ww  . ja v a2 s  . co m*/
public void transportConnected() {

    setState(STATE_READY);
    if (reconnectTask != null) {
        reconnectTask.cancel();
        reconnectTask = null;
    }
    resetTimeout();
    synchronized (outputBuffer) {
        if (transport.canSendBulk()) {
            ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
            this.outputBuffer = new ConcurrentLinkedQueue<String>();
            try {
                // DEBUG
                String[] texts = outputBuffer.toArray(new String[outputBuffer.size()]);
                log.debug("Bulk start:");
                for (String text : texts) {
                    log.debug("> " + text);
                }
                log.debug("Bulk end");
                // DEBUG END
                transport.sendBulk(texts);
            } catch (IOException e) {
                this.outputBuffer = outputBuffer;
            }
        } else {
            String text;
            while ((text = outputBuffer.poll()) != null) {
                sendPlain(text);
            }
        }
        this.keepAliveInQueue = false;
    }
}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServer.java

private void addUserConnection(String user, Session conn) {
    if (impl.userConnectedSocketsContainsKey(user)) {
        impl.getUserConnectedSocket(user).add(conn);
    } else {/*from  w  w w . j  av  a 2s .  co m*/
        Queue<Session> socketQueue = new ConcurrentLinkedQueue<>();
        socketQueue.add(conn);
        impl.putUserConnectedSocket(user, socketQueue);
    }
}

From source file:org.apache.hadoop.hbase.client.AsyncBatchRpcRetryingCaller.java

private void groupAndSend(Stream<Action> actions, int tries) {
    long locateTimeoutNs;
    if (operationTimeoutNs > 0) {
        locateTimeoutNs = remainingTimeNs();
        if (locateTimeoutNs <= 0) {
            failAll(actions, tries);//from w w w .  j  av a 2  s .c om
            return;
        }
    } else {
        locateTimeoutNs = -1L;
    }
    ConcurrentMap<ServerName, ServerRequest> actionsByServer = new ConcurrentHashMap<>();
    ConcurrentLinkedQueue<Action> locateFailed = new ConcurrentLinkedQueue<>();
    CompletableFuture.allOf(
            actions.map(action -> conn.getLocator().getRegionLocation(tableName, action.getAction().getRow(),
                    RegionLocateType.CURRENT, locateTimeoutNs).whenComplete((loc, error) -> {
                        if (error != null) {
                            error = translateException(error);
                            if (error instanceof DoNotRetryIOException) {
                                failOne(action, tries, error, EnvironmentEdgeManager.currentTime(), "");
                                return;
                            }
                            addError(action, error, null);
                            locateFailed.add(action);
                        } else {
                            computeIfAbsent(actionsByServer, loc.getServerName(), ServerRequest::new)
                                    .addAction(loc, action);
                        }
                    })).toArray(CompletableFuture[]::new))
            .whenComplete((v, r) -> {
                if (!actionsByServer.isEmpty()) {
                    send(actionsByServer, tries);
                }
                if (!locateFailed.isEmpty()) {
                    tryResubmit(locateFailed.stream(), tries);
                }
            });
}

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

private void addUserConnection(String user, NotebookSocket conn) {
    conn.setUser(user);/*from  w ww.  j  ava 2 s . co  m*/
    if (userConnectedSockets.containsKey(user)) {
        userConnectedSockets.get(user).add(conn);
    } else {
        Queue<NotebookSocket> socketQueue = new ConcurrentLinkedQueue<>();
        socketQueue.add(conn);
        userConnectedSockets.put(user, socketQueue);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeImpl.java

public RMNodeImpl(NodeId nodeId, RMContext context, String hostName, int cmPort, int httpPort, Node node,
        Resource capability, String nodeManagerVersion) {
    this.nodeId = nodeId;
    this.context = context;
    this.hostName = hostName;
    this.commandPort = cmPort;
    this.httpPort = httpPort;
    this.totalCapability = capability;
    this.nodeAddress = hostName + ":" + cmPort;
    this.httpAddress = hostName + ":" + httpPort;
    this.node = node;
    this.healthReport = "Healthy";
    this.lastHealthReportTime = System.currentTimeMillis();
    this.nodeManagerVersion = nodeManagerVersion;
    this.timeStamp = 0;

    this.latestNodeHeartBeatResponse.setResponseId(0);

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    this.readLock = lock.readLock();
    this.writeLock = lock.writeLock();

    this.stateMachine = stateMachineFactory.make(this);

    this.nodeUpdateQueue = new ConcurrentLinkedQueue<UpdatedContainerInfo>();

    this.containerAllocationExpirer = context.getContainerAllocationExpirer();
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void readMultiStream(String filename, int size, int loop, int batch) throws Exception {
    System.out.println(//from  w w w .  j a  va 2 s  .  co m
            "readMultiStream, filename " + filename + ", size " + size + ", loop " + loop + ", batch " + batch);

    //warmup
    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    for (int i = 0; i < warmup; i++) {
        CrailBuffer buf = fs.allocateBuffer().limit(size).slice();
        bufferQueue.add(buf);
    }
    warmUp(filename, warmup, bufferQueue);
    while (!bufferQueue.isEmpty()) {
        CrailBuffer buf = bufferQueue.poll();
        fs.freeBuffer(buf);
    }

    //benchmark
    System.out.println("starting benchmark...");
    fs.getStatistics().reset();
    CrailBuffer _buf = null;
    if (size == CrailConstants.BUFFER_SIZE) {
        _buf = fs.allocateBuffer();
    } else if (size < CrailConstants.BUFFER_SIZE) {
        CrailBuffer __buf = fs.allocateBuffer();
        __buf.clear().limit(size);
        _buf = __buf.slice();
    } else {
        _buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
    }
    ByteBuffer buf = _buf.getByteBuffer();
    for (int i = 0; i < loop; i++) {
        CrailBufferedInputStream multiStream = fs.lookup(filename).get().asMultiFile().getMultiStream(batch);
        double sumbytes = 0;
        long _sumbytes = 0;
        double ops = 0;
        buf.clear();
        long start = System.currentTimeMillis();
        int ret = multiStream.read(buf);
        while (ret >= 0) {
            sumbytes = sumbytes + ret;
            long _ret = (long) ret;
            _sumbytes += _ret;
            ops = ops + 1.0;
            buf.clear();
            ret = multiStream.read(buf);
        }
        long end = System.currentTimeMillis();
        multiStream.close();

        double executionTime = ((double) (end - start)) / 1000.0;
        double throughput = 0.0;
        double latency = 0.0;
        double sumbits = sumbytes * 8.0;
        if (executionTime > 0) {
            throughput = sumbits / executionTime / 1000.0 / 1000.0;
            latency = 1000000.0 * executionTime / ops;
        }

        System.out.println("round " + i + ":");
        System.out.println("bytes read " + _sumbytes);
        System.out.println("execution time " + executionTime);
        System.out.println("ops " + ops);
        System.out.println("throughput " + throughput);
        System.out.println("latency " + latency);
    }

    fs.getStatistics().print("close");
}

From source file:org.geowebcache.storage.JobObject.java

/**
 * Deal with ensuring a deserialized job is in a valid state.
 * Between extJS and XStream, some of the JSON isn't converted properly. 
 * This method makes sure the job is in a state the system would expect it to be in.
 * It's mainly stuff that was null turning into stuff that is an empty string - and it's extJS doing it.
 * @return/*  w  w  w.  j a v  a 2 s  .  com*/
 */
private Object readResolve() {
    if (this.schedule != null && this.schedule.equals("")) {
        this.schedule = null;
    }

    if (this.encodedParameters != null && this.encodedParameters.equals("")) {
        this.encodedParameters = null;
    }

    newLogs = new ConcurrentLinkedQueue<JobLogObject>();

    return this;
}

From source file:de.mmbbs.io.socket.IOConnection.java

/**
 * Transport connected./*ww w.j av a 2  s.c o  m*/
 * 
 * {@link IOTransport} calls this when a connection is established.
 */
public synchronized void transportConnected() {
    setState(STATE_READY);
    if (reconnectTask != null) {
        reconnectTask.cancel();
        reconnectTask = null;
    }
    if (heartBeatTask != null) {
        heartBeatTask.cancel();
    }
    heartBeatTask = new HeartBeatTask(); // heartbeat loop
    backgroundTimer.schedule(heartBeatTask, heartbeatTimeout, heartbeatTimeout);
    resetTimeout();
    if (transport.canSendBulk()) {
        ConcurrentLinkedQueue<String> outputBuffer = this.outputBuffer;
        this.outputBuffer = new ConcurrentLinkedQueue<String>();
        try {
            // DEBUG
            String[] texts = outputBuffer.toArray(new String[outputBuffer.size()]);
            logger.info("Bulk start:");
            for (String text : texts) {
                logger.info("> " + text);
            }
            logger.info("Bulk end");
            // DEBUG END
            transport.sendBulk(texts);
        } catch (IOException e) {
            this.outputBuffer = outputBuffer;
        }
    } else {
        String text;
        while ((text = outputBuffer.poll()) != null)
            sendPlain(text);
    }
    this.keepAliveInQueue = false;
}