Example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

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

Introduction

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

Prototype

public LinkedBlockingQueue() 

Source Link

Document

Creates a LinkedBlockingQueue with a capacity of Integer#MAX_VALUE .

Usage

From source file:de.hshannover.f4.trust.ironcontrol.logic.ResultNotificationManager.java

public ResultNotificationManager(Context context) {
    logger.log(Level.DEBUG, "New ResultNotificationManager()");

    this.context = context;
    this.r = context.getResources();
    this.mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    this.prefData = PreferenceManager.getDefaultSharedPreferences(context);
    this.newEvents = new LinkedBlockingQueue<PollResult>();
    this.notifyId = 10;
}

From source file:com.bittorrent.mpetazzoni.client.peer.PeerExchange.java

/**
 * Initialize and start a new peer exchange.
 *
 * @param peer The remote peer to communicate with.
 * @param torrent The torrent we're exchanging on with the peer.
 * @param channel A channel on the connected socket to the peer.
 *///from   w  w  w  .  j av  a 2 s  .  c  om
public PeerExchange(SharingPeer peer, SharedTorrent torrent, SocketChannel channel) throws SocketException {
    this.peer = peer;
    this.torrent = torrent;
    this.channel = channel;

    this.listeners = new HashSet<MessageListener>();
    this.sendQueue = new LinkedBlockingQueue<PeerMessage>();

    if (!this.peer.hasPeerId()) {
        throw new IllegalStateException("Peer does not have a " + "peer ID. Was the handshake made properly?");
    }

    this.in = new IncomingThread();
    this.in.setName("bt-peer(" + this.peer.getShortHexPeerId() + ")-recv");

    this.out = new OutgoingThread();
    this.out.setName("bt-peer(" + this.peer.getShortHexPeerId() + ")-send");
    this.out.setDaemon(true);

    // Automatically start the exchange activity loops
    this.stop = false;
    this.in.start();
    this.out.start();

    logger.debug("Started peer exchange with {} for {}.", this.peer, this.torrent);

    // If we have pieces, start by sending a BITFIELD message to the peer.
    BitSet pieces = this.torrent.getCompletedPieces();
    if (pieces.cardinality() > 0) {
        this.send(PeerMessage.BitfieldMessage.craft(pieces));
    }
}

From source file:com.precioustech.fxtrading.tradingbot.strategies.CopyTwitterStrategyTest.java

@Test
public void harvestAndTradeTest() throws InterruptedException {
    CopyTwitterStrategy<String> copyTwitterStrategy = new CopyTwitterStrategy<String>();
    FXTweetHandler<String> tweetHandlerFoo = createTweetHandlerFoo(copyTwitterStrategy);
    BlockingQueue<TradingDecision<String>> orderQueue = new LinkedBlockingQueue<TradingDecision<String>>();
    copyTwitterStrategy.orderQueue = orderQueue;
    copyTwitterStrategy.init();/*from w  w  w  .j av  a  2  s  .  com*/
    Tweet tweet1 = mock(Tweet.class);
    Collection<Tweet> footweets = Lists.newArrayList(tweet1);
    NewFXTradeTweet<String> newTrade = mock(NewFXTradeTweet.class);
    when(tweetHandlerFoo.findNewTweets()).thenReturn(footweets);
    when(tweetHandlerFoo.handleTweet(tweet1)).thenReturn(newTrade);
    when(newTrade.getAction()).thenReturn(TradingSignal.SHORT);
    TradeableInstrument<String> euraud = new TradeableInstrument<String>("EUR_AUD");
    when(newTrade.getInstrument()).thenReturn(euraud);
    double[] profits = { 11.32, 17.7, 8.2, 19.0, 44.5, -11.0, 10, 25.5 };
    Collection<CloseFXTradeTweet<String>> closedTrades = createClosedTrades(profits);
    footweets = Lists.newArrayList();
    for (CloseFXTradeTweet<String> closeTradeTweet : closedTrades) {
        Tweet tweet = mock(Tweet.class);
        when(tweetHandlerFoo.handleTweet(tweet)).thenReturn(closeTradeTweet);
        footweets.add(tweet);
    }
    when(tweetHandlerFoo.findHistoricPnlTweetsForInstrument(euraud)).thenReturn(footweets);
    copyTwitterStrategy.harvestAndTrade();
    TradingDecision<String> decision = orderQueue.take();
    assertEquals(TradingSignal.SHORT, decision.getSignal());
    assertEquals(euraud, decision.getInstrument());
}

From source file:com.adaptris.http.HttpListener.java

/**
 * Add a request processor to the list/*from  w w w  . j  a va2  s.  c o m*/
 * 
 * @param rp the request processor.
 * @throws HttpException on error.
 */
public synchronized void addRequestProcessor(RequestProcessor rp) throws HttpException {
    try {

        String uri = rp.getUri();
        LinkedBlockingQueue list = (LinkedBlockingQueue) requestProcessors.get(uri);
        if (list == null) {
            list = new LinkedBlockingQueue();
        }
        list.put(rp);
        requestProcessors.put(uri, list);
    } catch (Exception e) {
        throw new HttpException(e);
    }
}

From source file:com.espertech.esper.example.stockticker.TestStockTickerMultithreaded.java

public void performTest(int numberOfThreads, int numberOfTicksToSend, int ratioPriceOutOfLimit,
        int numberOfSecondsWaitForCompletion) {
    final int totalNumTicks = numberOfTicksToSend + 2 * TestStockTickerGenerator.NUM_STOCK_NAMES;

    log.info(".performTest Generating data, numberOfTicksToSend=" + numberOfTicksToSend
            + "  ratioPriceOutOfLimit=" + ratioPriceOutOfLimit);

    StockTickerEventGenerator generator = new StockTickerEventGenerator();
    LinkedList stream = generator.makeEventStream(numberOfTicksToSend, ratioPriceOutOfLimit,
            TestStockTickerGenerator.NUM_STOCK_NAMES,
            StockTickerRegressionConstants.PRICE_LIMIT_PCT_LOWER_LIMIT,
            StockTickerRegressionConstants.PRICE_LIMIT_PCT_UPPER_LIMIT,
            StockTickerRegressionConstants.PRICE_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_UPPER_LIMIT,
            true);//from   w ww  .j a v  a2 s  .  c  o  m

    log.info(".performTest Send limit and initial tick events - singlethreaded");
    for (int i = 0; i < TestStockTickerGenerator.NUM_STOCK_NAMES * 2; i++) {
        Object theEvent = stream.removeFirst();
        epService.getEPRuntime().sendEvent(theEvent);
    }

    log.info(".performTest Loading thread pool work queue, numberOfRunnables=" + stream.size());

    ThreadPoolExecutor pool = new ThreadPoolExecutor(0, numberOfThreads, 99999, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    for (Object theEvent : stream) {
        SendEventRunnable runnable = new SendEventRunnable(epService, theEvent);
        pool.execute(runnable);
    }

    log.info(".performTest Starting thread pool, threads=" + numberOfThreads);
    pool.setCorePoolSize(numberOfThreads);

    log.info(".performTest Listening for completion");
    EPRuntimeUtil.awaitCompletion(epService.getEPRuntime(), totalNumTicks, numberOfSecondsWaitForCompletion, 1,
            10);

    pool.shutdown();

    // Check results : make sure the given ratio of out-of-limit stock prices was reported
    int expectedNumEmitted = (numberOfTicksToSend / ratioPriceOutOfLimit) + 1;
    assertTrue(listener.getSize() == expectedNumEmitted);

    log.info(".performTest Done test");
}

From source file:org.muckebox.android.net.DownloadServer.java

public DownloadServer(String mimeType) {
    super(LOG_TAG);

    mMimeType = mimeType;//from w  w w  . j  ava  2s. c  om
    mQueue = new LinkedBlockingQueue<ByteBuffer>();

    mPort = getRandomPort();

    initHttpServer();
}

From source file:com.turn.ttorrent.client.peer.PeerExchange.java

/**
 * Initialize and start a new peer exchange.
 *
 * @param peer The remote peer to communicate with.
 * @param torrent The torrent we're exchanging on with the peer.
 * @param channel A channel on the connected socket to the peer.
 *///from w  ww  .j  av  a  2  s  .  c  o  m
public PeerExchange(SharingPeer peer, SharedTorrent torrent, SocketChannel channel) throws SocketException {
    this.peer = peer;
    this.torrent = torrent;
    this.channel = channel;

    this.listeners = new HashSet<MessageListener>();
    this.sendQueue = new LinkedBlockingQueue<PeerMessage>();

    if (!this.peer.hasPeerId()) {
        throw new IllegalStateException("Peer does not have a " + "peer ID. Was the handshake made properly?");
    }

    this.in = new IncomingThread();
    this.in.setName("bt-peer(" + this.peer.getShortHexPeerId() + ")-recv");

    this.out = new OutgoingThread();
    this.out.setName("bt-peer(" + this.peer.getShortHexPeerId() + ")-send");
    this.out.setDaemon(true);

    this.stop = false;

    logger.debug("Started peer exchange with {} for {}.", this.peer, this.torrent);

    // If we have pieces, start by sending a BITFIELD message to the peer.
    BitSet pieces = this.torrent.getCompletedPieces();
    if (pieces.cardinality() > 0) {
        this.send(PeerMessage.BitfieldMessage.craft(pieces, torrent.getPieceCount()));
    }
}

From source file:io.seldon.api.state.ZkABTestingUpdater.java

@Override
public void run() {
    logger.info("Starting");
    try {//ww  w.  j  a v a 2 s.c  om
        while (keepRunning) {
            boolean error = false;
            try {

                CuratorFramework client = null;
                boolean ok = false;
                for (int attempts = 0; attempts < 4 && !ok; attempts++) {
                    client = curatorHandler.getCurator().usingNamespace(clientName);
                    logger.info("Waiting until zookeeper connected");
                    ok = client.getZookeeperClient().blockUntilConnectedOrTimedOut();
                    if (ok)
                        logger.info("zookeeper connected on attempt " + attempts);
                    else {
                        logger.error("Timed out waiting for zookeeper connect : attempt " + attempts);
                    }
                }
                if (!ok) {
                    logger.error("Failed to connect to zookeeper after multiple attempts - STOPPING");
                    return;
                }
                queue = new LinkedBlockingQueue<>();
                Watcher watcher = new Watcher() {
                    boolean expired;

                    @Override
                    public void process(WatchedEvent event) {
                        try {
                            if (event.getPath() != null)
                                queue.put(event.getPath());
                            else {
                                logger.warn("Unexpected event " + event.getType().name() + " -> "
                                        + event.toString());
                                switch (event.getState()) {
                                case SyncConnected: {
                                }
                                    break;
                                case Expired: {
                                    queue.put("");
                                }
                                    break;
                                case Disconnected: {
                                }
                                    break;
                                }
                            }
                        } catch (InterruptedException e) {
                            throw new Error(e);
                        }
                    }
                };

                logger.info("Checking path " + DYNAMIC_PARAM_PATH + " exists");
                if (client.checkExists().forPath(DYNAMIC_PARAM_PATH) == null) {
                    logger.warn("Path " + DYNAMIC_PARAM_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(DYNAMIC_PARAM_PATH);
                }

                logger.info("Checking path " + AB_ALG_PATH + " exists");
                if (client.checkExists().forPath(AB_ALG_PATH) == null) {
                    logger.warn("Path " + AB_ALG_PATH + " does not exist for client " + clientName
                            + " creating...");
                    client.create().forPath(AB_ALG_PATH);
                }

                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);

                boolean restart = false;
                while (keepRunning && !restart) {

                    String path = queue.take();
                    if (!StringUtils.isEmpty(path)) {
                        logger.info("Alg Path changed " + path);

                        System.out.println("Alg Path changed " + path);

                        if (path.endsWith(DYNAMIC_PARAM_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(DYNAMIC_PARAM_PATH);
                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                DynamicParameterBean bean = (DynamicParameterBean) in.readObject();
                                in.close();
                                logger.info("Updating dynamic parameter: " + bean.getName()
                                        + " and setting to value: " + bean.getValue() + " for client "
                                        + clientName);
                                DynamicParameterServer.setParameterBean(clientName, bean);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                            }

                        } else if (path.endsWith(AB_ALG_PATH)) {
                            try {
                                byte[] bytes = client.getData().forPath(AB_ALG_PATH);

                                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
                                ABTest abTest = (ABTest) in.readObject();
                                in.close();
                                logger.info("Updating Algorithm percentage for client " + clientName + " to "
                                        + abTest.toString());
                                ABTestingServer.setABTest(clientName, abTest);
                                numUpdates++;
                            } catch (ClassNotFoundException e) {
                                logger.error("Can't find class ", e);
                            } catch (IOException e) {
                                logger.error("Failed to deserialize algorithm for client " + clientName, e);
                            } finally {
                                client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                            }
                        } else {
                            logger.error("Unknown path " + path + " changed so reseting watchers");
                        }
                    } else {
                        //client.getData().usingWatcher(watcher).forPath(DYNAMIC_PARAM_PATH);
                        //client.getData().usingWatcher(watcher).forPath(AB_ALG_PATH);
                        logger.warn("Will try to restart");
                        restart = true;
                    }

                }

            } catch (IOException e) {
                logger.error("Exception trying to create sk client ", e);
                error = true;
            } catch (Exception e) {
                logger.error("Exception from zookeeper client ", e);
                error = true;
            } finally {

            }

            if (keepRunning && error) {
                logger.info("Sleeping " + sleepTime);
                Thread.sleep(sleepTime);
                if (sleepTime * 2 < maxSleepTime)
                    sleepTime = sleepTime * 2;
                error = false;
            }

        }
    } catch (InterruptedException e) {
        logger.warn("Sleep interuppted ", e);
    }
    logger.info("Stopping");
}

From source file:com.connection.factory.FtpConnectionApacheLib.java

@Override
public List<RemoteFileObject> readAllFilesWalkinPath(String remotePath) {
    List<RemoteFileObject> willReturnObject = new ArrayList<>();
    Queue<RemoteFileObject> directorylist = new LinkedBlockingQueue<>();
    RemoteFileObject object = null;/*  w w w .  j a v a  2s. c  o  m*/
    object = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
    object.setDirectPath(remotePath);
    directorylist.add(object);
    try {
        while (!directorylist.isEmpty()) {
            object = directorylist.poll();
            FTPFile[] fileListTemp = _ftpObj.listFiles(object.getPath());
            for (FTPFile each : fileListTemp) {
                RemoteFileObject objectTemp = null;
                if (each.isDirectory()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.DIRECTORY);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    directorylist.add(objectTemp);
                } else if (each.isFile()) {
                    objectTemp = new FtpApacheFileObject(FileInfoEnum.FILE);
                    objectTemp.setFileName(each.getName());
                    objectTemp.setAbsolutePath(object.getPath());
                    objectTemp.setFileSize(each.getSize());
                    objectTemp.setFileType();
                    objectTemp.setDate(each.getTimestamp().getTime());
                    willReturnObject.add(objectTemp);
                }
            }
            object = null;
            fileListTemp = null;
        }

    } catch (IOException ex) {
        return null;
    } catch (ConnectionException ex) {

    }
    return willReturnObject;
}

From source file:org.kaaproject.kaa.server.verifiers.gplus.verifier.GplusUserVerifier.java

@Override
public void start() {
    LOG.info("user verifier started");
    threadPool = new ThreadPoolExecutor(configuration.getMinParallelConnections(),
            configuration.getMaxParallelConnections(), configuration.getKeepAliveTimeMilliseconds(),
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(configuration.getMaxParallelConnections());
    httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
}