Example usage for java.util.concurrent ArrayBlockingQueue poll

List of usage examples for java.util.concurrent ArrayBlockingQueue poll

Introduction

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

Prototype

public E poll(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int capacity = 10;
    ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

    for (int i = 0; i < 10; i++) {
        queue.add(i);/*from w w  w.j  av a  2 s.  co m*/
    }

    System.out.println(queue.poll(10, TimeUnit.MINUTES));
}

From source file:com.taobao.tdhs.client.statement.BatchStatementImpl.java

private TDHSResponse[] do_real_response(ArrayBlockingQueue<BasePacket> queue) throws TDHSException {
    BasePacket ret = null;//from www .  j ava 2s  .c  om
    try {
        ret = queue.poll(getTimeOut(), TimeUnit.MILLISECONDS);
        if (ret == null) {
            throw new TDHSTimeoutException("TimeOut");
        }
        if (!TDHSResponseEnum.ClientStatus.MULTI_STATUS.equals(ret.getClientStatus())) {
            if (ret.getClientStatus() != null && ret.getClientStatus().getStatus() >= 400
                    && ret.getClientStatus().getStatus() < 600) {
                throw new TDHSBatchException(
                        new TDHSResponse(ret.getClientStatus(), null, ret.getData(), charsetName));
            } else {
                throw new TDHSException("unknown response code! ["
                        + (ret.getClientStatus() != null ? String.valueOf(ret.getClientStatus().getStatus())
                                : "")
                        + "]");
            }
        }
        if (ret.getBatchNumber() != batchRequest.size()) {
            throw new TDHSException("unmatch batch size! request is[" + String.valueOf(batchRequest.size())
                    + "], response is [" + String.valueOf(ret.getBatchNumber()) + "]");
        }

        TDHSResponse result[] = new TDHSResponse[batchRequest.size()];
        int i = 0;
        for (internal_struct is : batchRequest) {
            result[i++] = do_response(responses.get(is.getPacket().getSeqId()), is.getMetaData(),
                    is.getCharsetName());
        }
        return result;
    } catch (InterruptedException e) {
        throw new TDHSException(e);
    }
}

From source file:com.taobao.adfs.database.tdhsocket.client.statement.BatchStatementImpl.java

private TDHSResponse[] do_real_response(ArrayBlockingQueue<BasePacket> queue) throws TDHSException {
    BasePacket ret = null;/*from  w w w .  j  a v  a 2  s . c  o m*/
    try {
        ret = queue.poll(getTimeOut(), TimeUnit.MILLISECONDS);
        if (ret == null) {
            throw new TDHSTimeoutException("TimeOut");
        }
        if (!TDHSResponseEnum.ClientStatus.MULTI_STATUS.equals(ret.getClientStatus())) {
            if (ret.getClientStatus() != null && ret.getClientStatus().getStatus() >= 400
                    && ret.getClientStatus().getStatus() < 600) {
                throw new TDHSBatchException(
                        new TDHSResponse(ret.getClientStatus(), null, ret.getData(), charestName));
            } else {
                throw new TDHSException("unknown response code! ["
                        + (ret.getClientStatus() != null ? String.valueOf(ret.getClientStatus().getStatus())
                                : "")
                        + "]");
            }
        }
        if (ret.getBatchNumber() != batchRequest.size()) {
            throw new TDHSException("unmatch batch size! request is[" + String.valueOf(batchRequest.size())
                    + "], response is [" + String.valueOf(ret.getBatchNumber()) + "]");
        }

        TDHSResponse result[] = new TDHSResponse[batchRequest.size()];
        int i = 0;
        for (internal_struct is : batchRequest) {
            result[i++] = do_response(responses.get(is.getPacket().getSeqId()), is.getFieldNames(),
                    is.getCharestName());
        }
        return result;
    } catch (InterruptedException e) {
        throw new TDHSException(e);
    }
}

From source file:com.taobao.adfs.database.tdhsocket.client.statement.StatementImpl.java

protected TDHSResponse do_response(ArrayBlockingQueue<BasePacket> queue, List<String> fieldNames,
        String charestName) throws TDHSException {
    ByteArrayOutputStream retData = new ByteArrayOutputStream();
    try {//from w ww .  jav a2s.  c  o m
        while (true) {
            BasePacket ret = null;
            ret = queue.poll(timeOut, TimeUnit.MILLISECONDS);
            if (ret == null) {
                throw new TDHSTimeoutException("TimeOut");
            } else {
                if (TDHSResponseEnum.ClientStatus.ACCEPT.equals(ret.getClientStatus())) {
                    retData.write(ret.getData());
                } else if (TDHSResponseEnum.ClientStatus.OK.equals(ret.getClientStatus())) {
                    retData.write(ret.getData());
                    return new TDHSResponse(ret.getClientStatus(), fieldNames, retData.toByteArray(),
                            charestName);
                } else if (ret.getClientStatus() != null && ret.getClientStatus().getStatus() >= 400
                        && ret.getClientStatus().getStatus() < 600) {
                    return new TDHSResponse(ret.getClientStatus(), fieldNames, ret.getData(), charestName);
                } else {
                    throw new TDHSException("unknown response code! ["
                            + (ret.getClientStatus() != null ? String.valueOf(ret.getClientStatus().getStatus())
                                    : "")
                            + "]");
                }
            }
        }
    } catch (InterruptedException e) {
        throw new TDHSException(e);
    } catch (IOException e) {
        throw new TDHSException(e);
    }
}

From source file:com.taobao.tdhs.client.statement.StatementImpl.java

protected TDHSResponse do_response(ArrayBlockingQueue<BasePacket> queue, TDHSMetaData metaData,
        String charsetName) throws TDHSException {
    ByteArrayOutputStream retData = new ByteArrayOutputStream();
    try {//from   w  w  w  .  ja v a2s .c om
        while (true) {
            BasePacket ret = null;
            ret = queue.poll(timeOut, TimeUnit.MILLISECONDS);
            if (ret == null) {
                throw new TDHSTimeoutException("TimeOut");
            } else {
                if (TDHSResponseEnum.ClientStatus.ACCEPT.equals(ret.getClientStatus())) {
                    retData.write(ret.getData());
                } else if (TDHSResponseEnum.ClientStatus.OK.equals(ret.getClientStatus())) {
                    retData.write(ret.getData());
                    return new TDHSResponse(ret.getClientStatus(), metaData, retData.toByteArray(),
                            charsetName);
                } else if (ret.getClientStatus() != null && ret.getClientStatus().getStatus() >= 400
                        && ret.getClientStatus().getStatus() < 600) {
                    return new TDHSResponse(ret.getClientStatus(), metaData, ret.getData(), charsetName);
                } else {
                    throw new TDHSException("unknown response code! ["
                            + (ret.getClientStatus() != null ? String.valueOf(ret.getClientStatus().getStatus())
                                    : "")
                            + "]");
                }
            }
        }
    } catch (InterruptedException e) {
        throw new TDHSException(e);
    } catch (IOException e) {
        throw new TDHSException(e);
    }
}

From source file:code.google.nfs.rpc.client.AbstractClient.java

private Object invokeSyncIntern(RequestWrapper wrapper) throws Exception {
    long beginTime = System.currentTimeMillis();
    ArrayBlockingQueue<Object> responseQueue = new ArrayBlockingQueue<Object>(1);
    responses.put(wrapper.getId(), responseQueue);
    ResponseWrapper responseWrapper = null;
    try {/*from  w  w w  .j a  v a  2  s .c o m*/
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug("client ready to send message,request id: " + wrapper.getId());
        }
        getClientFactory().checkSendLimit();
        sendRequest(wrapper, wrapper.getTimeout());
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug(
                    "client write message to send buffer,wait for response,request id: " + wrapper.getId());
        }
    } catch (Exception e) {
        responses.remove(wrapper.getId());
        responseQueue = null;
        LOGGER.error("send request to os sendbuffer error", e);
        throw e;
    }
    Object result = null;
    try {
        result = responseQueue.poll(wrapper.getTimeout() - (System.currentTimeMillis() - beginTime),
                TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        responses.remove(wrapper.getId());
        LOGGER.error("Get response error", e);
        throw new Exception("Get response error", e);
    }
    responses.remove(wrapper.getId());

    if (PRINT_CONSUME_MINTIME > 0 && isWarnEnabled) {
        long consumeTime = System.currentTimeMillis() - beginTime;
        if (consumeTime > PRINT_CONSUME_MINTIME) {
            LOGGER.warn("client.invokeSync consume time: " + consumeTime + " ms, server is: " + getServerIP()
                    + ":" + getServerPort() + " request id is:" + wrapper.getId());
        }
    }
    if (result == null) {
        String errorMsg = "receive response timeout(" + wrapper.getTimeout() + " ms),server is: "
                + getServerIP() + ":" + getServerPort() + " request id is:" + wrapper.getId();
        throw new Exception(errorMsg);
    }

    if (result instanceof ResponseWrapper) {
        responseWrapper = (ResponseWrapper) result;
    } else if (result instanceof List) {
        @SuppressWarnings("unchecked")
        List<ResponseWrapper> responseWrappers = (List<ResponseWrapper>) result;
        for (ResponseWrapper response : responseWrappers) {
            if (response.getRequestId() == wrapper.getId()) {
                responseWrapper = response;
            } else {
                putResponse(response);
            }
        }
    } else {
        throw new Exception("only receive ResponseWrapper or List as response");
    }
    try {
        // do deserialize in business threadpool
        if (responseWrapper.getResponse() instanceof byte[]) {
            String responseClassName = null;
            if (responseWrapper.getResponseClassName() != null) {
                responseClassName = new String(responseWrapper.getResponseClassName());
            }
            // avoid server no return object
            if (((byte[]) responseWrapper.getResponse()).length == 0) {
                responseWrapper.setResponse(null);
            } else {
                Object responseObject = Codecs.getDecoder(responseWrapper.getCodecType())
                        .decode(responseClassName, (byte[]) responseWrapper.getResponse());
                if (responseObject instanceof Throwable) {
                    responseWrapper.setException((Throwable) responseObject);
                } else {
                    responseWrapper.setResponse(responseObject);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Deserialize response object error", e);
        throw new Exception("Deserialize response object error", e);
    }
    if (responseWrapper.isError()) {
        Throwable t = responseWrapper.getException();
        t.fillInStackTrace();
        String errorMsg = "server error,server is: " + getServerIP() + ":" + getServerPort() + " request id is:"
                + wrapper.getId();
        LOGGER.error(errorMsg, t);
        throw new Exception(errorMsg, t);
    }
    return responseWrapper.getResponse();
}

From source file:com.taobao.common.tfs.comm.TfsClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TfsException {
    if (isDebugEnabled) {
        log.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }//  w ww  .ja  v a2 s . com
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {

            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed: "
                    + !session.isConnected();

            try {
                putResponse(packet.getChid(), new TfsException(error));
            } catch (TfsException e) {
                // should never happen
                log.error("put response fail", e);
            }

            // close this session
            if (session.isConnected()) {
                session.close();
            } else {
                TfsClientFactory.getInstance().removeClient(key);
            }
        }

    });

    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) { // timeout
            return null;
        } else if (response instanceof TfsException) {
            throw (TfsException) response;
        }
    } catch (InterruptedException e) {
        throw new TfsException("tfs client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        log.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:com.taobao.tair.comm.TairClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TairClientException {
    if (isDebugEnabled) {
        LOGGER.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }/*from w  w  w  . java 2s  .co  m*/
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {
            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tair server error [" + packet.getChid() + "], tair server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed :"
                    + !session.isConnected();
            LOGGER.warn(error);
            TairResponse response = new TairResponse();
            response.setRequestId(packet.getChid());
            response.setResponse(new TairClientException(error));
            try {
                putResponse(packet.getChid(), response.getResponse());
            } catch (TairClientException e) {
                // IGNORE,should not happen
            }
            // close this session
            if (session.isConnected())
                session.close();
            else
                clientFactory.removeClient(key);
        }

    });
    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) {
            throw new TairClientException("tair client invoke timeout,timeout is: " + timeout
                    + ",requestId is: " + packet.getChid() + "request type:" + packet.getClass().getName());
        } else if (response instanceof TairClientException) {
            throw (TairClientException) response;
        }
    } catch (InterruptedException e) {
        throw new TairClientException("tair client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        LOGGER.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
        LOGGER.debug("current responses size: " + responses.size());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:net.sf.xfd.provider.PublicProvider.java

final boolean checkAccess(Uri uri, String grantMode, String necessaryMode) {
    try {//from www  .  ja  va 2 s  .c o  m
        verifyMac(uri, grantMode, necessaryMode);

        return true;
    } catch (FileNotFoundException fnfe) {
        final Context context = getContext();

        assert context != null;

        ObjectIntMap<String> decisions = null;

        final String caller = getCallingPackage();

        if (!TextUtils.isEmpty(caller)) {
            decisions = accessCache.get(uri.getPath());
            if (decisions == null) {
                decisions = new ObjectIntHashMap<>();
            } else {
                //noinspection SynchronizationOnLocalVariableOrMethodParameter
                synchronized (decisions) {
                    final int decision = decisions.get(caller);

                    switch (decision) {
                    case RESPONSE_ALLOW:
                        return true;
                    }
                }
            }
        }

        final ArrayBlockingQueue<Bundle> queue = new ArrayBlockingQueue<>(1);

        //noinspection RestrictedApi
        final ResultReceiver receiver = new ResultReceiver(new Handler(Looper.getMainLooper())) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                try {
                    queue.offer(resultData, 4, TimeUnit.SECONDS);
                } catch (InterruptedException ignored) {
                }
            }
        };

        try {
            final Intent intent = authActivityIntent(context);

            if (intent == null)
                return false;

            final Bundle result;

            final CharSequence resolved = base.resolve(uri.getPath());

            // try to ensure, that no more than one dialog can appear at once
            uxLock.lockInterruptibly();
            try {
                context.startActivity(intent.putExtra(EXTRA_MODE, necessaryMode).putExtra(EXTRA_CALLER, caller)
                        .putExtra(EXTRA_UID, Binder.getCallingUid()).putExtra(EXTRA_CALLBACK, receiver)
                        .putExtra(EXTRA_PATH, resolved));

                result = queue.poll(10, TimeUnit.SECONDS);
            } finally {
                uxLock.unlock();
            }

            int decision = RESPONSE_DENY;

            if (result != null) {
                decision = result.getInt(EXTRA_RESPONSE, -1);
            }

            if (decision == RESPONSE_ALLOW) {
                if (decisions != null) {
                    //noinspection SynchronizationOnLocalVariableOrMethodParameter
                    synchronized (decisions) {
                        decisions.put(caller, RESPONSE_ALLOW);

                        accessCache.put(uri.getPath(), decisions);
                    }
                }

                return true;
            }
        } catch (InterruptedException ignored) {
        }
    }

    return false;
}

From source file:org.kurento.rabbitmq.RabbitTemplate.java

protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override/* ww  w .  j a  v a 2s  .  c om*/
        public Message doInRabbit(Channel channel) throws Exception {
            final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);

            Assert.isNull(message.getMessageProperties().getReplyTo(),
                    "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
            DeclareOk queueDeclaration = channel.queueDeclare();
            String replyTo = queueDeclaration.getQueue();
            message.getMessageProperties().setReplyTo(replyTo);

            String consumerTag = UUID.randomUUID().toString();
            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MessageProperties messageProperties = messagePropertiesConverter
                            .toMessageProperties(properties, envelope, encoding);
                    Message reply = new Message(body, messageProperties);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Message received " + reply);
                    }
                    try {
                        replyHandoff.put(reply);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            };
            channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);
            doSend(channel, exchange, routingKey, message, null);
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            channel.basicCancel(consumerTag);
            return reply;
        }
    });
}