List of usage examples for java.util.concurrent LinkedBlockingQueue poll
public E poll(long timeout, TimeUnit unit) throws InterruptedException
From source file:com.YOMPsolutions.YOMP.mobile.service.YOMPDataSyncService.java
/** * Loads metric data from the server/*from w w w .j a va 2 s.co m*/ * * @param metricId (optional) The metric Id to get the data. If metricId is {@code null} then * loads data for all metrics at once. * @param from return records from this date * @param to return records up to this date * @see com.numenta.core.service.YOMPClient#getMetricData */ private void loadMetricData(final String metricId, final long from, final long to) throws YOMPException, IOException { if (getClient() == null) { Log.w(TAG, "Not connected to any server yet"); return; } final CoreDatabase database = YOMPApplication.getDatabase(); // Blocking queue holding metric data waiting to be saved to the // database. This queue will be filled by the YOMPClient as it downloads // the metric data and it will be emptied by the databaseTask as is // saves the data to the database final LinkedBlockingQueue<MetricData> pending = new LinkedBlockingQueue<>( MAX_PENDING_METRIC_DATA_IO_BUFFER); // Background task used save metric data to the database. This task will // wait for metric data to arrive from the server and save them to the // database in batches until it finds the end of the queue marked by // METRIC_DATA_EOF or it times out after 60 seconds final Future<?> databaseTask = getService().getIOThreadPool().submit(new Runnable() { @Override public void run() { // Make the batch size 1 hour for all metrics or one week for // single metric int batchSize = metricId == null ? DataUtils.MILLIS_PER_HOUR : 24 * 7 * DataUtils.MILLIS_PER_HOUR; // Save metrics in batches, 24 hours at the time final List<MetricData> batch = new ArrayList<>(); // Tracks batch timestamp. Once the metric timestamp is greater // than the batch timestamp, a new batch is created long batchTimestamp = 0; try { // Process all pending metric data until the METRIC_DATA_EOF // is found or a timeout is reached MetricData metricData; while ((metricData = pending.poll(60, TimeUnit.SECONDS)) != METRIC_DATA_EOF && metricData != null) { // Add metric data to batch regardless of the timestamp. // At this point we may receive stale metric data with // lower timestamp after we receive the latest data with // the current timestamp. As a side effect, you may see // gaps in the data as described in MER-1524 batch.add(metricData); // Process batches if (metricData.getTimestamp() > batchTimestamp) { // Calculate next batch timestamp batchTimestamp = metricData.getTimestamp() + batchSize; if (database.addMetricDataBatch(batch)) { Log.d(TAG, "Saving " + batch.size() + " new records"); // Notify receivers new data has arrived fireMetricDataChangedEvent(); } batch.clear(); } } // Last batch if (!batch.isEmpty()) { if (database.addMetricDataBatch(batch)) { Log.d(TAG, "Received " + batch.size() + " records"); // Notify receivers new data has arrived fireMetricDataChangedEvent(); } } } catch (InterruptedException e) { Log.w(TAG, "Interrupted while loading metric data"); } } }); try { // Get new data from server getClient().getMetricData(metricId, new Date(from), new Date(to), new YOMPClient.DataCallback<MetricData>() { @Override public boolean onData(MetricData metricData) { // enqueue data for saving try { Metric metric = database.getMetric(metricData.getMetricId()); if (metric == null) { Log.w(TAG, "Received data for unknown metric:" + metricData.getMetricId()); return true; } pending.put(metricData); } catch (InterruptedException e) { pending.clear(); Log.w(TAG, "Interrupted while loading metric data"); return false; } return true; } }); // Mark the end of the records pending.add(METRIC_DATA_EOF); // Wait for the database task to complete databaseTask.get(); } catch (InterruptedException e) { Log.w(TAG, "Interrupted while loading metric data"); } catch (ExecutionException e) { Log.e(TAG, "Failed to load metric data", e); } }
From source file:com.offbynull.portmapper.pcp.PcpController.java
private <T extends PcpResponse> T attemptRequest(ByteBuffer sendBuffer, int attempt, Creator<T> creator) throws InterruptedException { final LinkedBlockingQueue<ByteBuffer> recvBufferQueue = new LinkedBlockingQueue<>(); UdpCommunicatorListener listener = new UdpCommunicatorListener() { @Override/*from www . j av a 2 s . c om*/ public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel, ByteBuffer packet) { if (channel != unicastChannel) { return; } recvBufferQueue.add(packet); } }; // timeout duration should double each iteration, starting from 250 according to spec // i = 1, maxWaitTime = (1 << (1-1)) * 250 = (1 << 0) * 250 = 1 * 250 = 250 // i = 2, maxWaitTime = (1 << (2-1)) * 250 = (1 << 1) * 250 = 2 * 250 = 500 // i = 3, maxWaitTime = (1 << (3-1)) * 250 = (1 << 2) * 250 = 4 * 250 = 1000 // i = 4, maxWaitTime = (1 << (4-1)) * 250 = (1 << 3) * 250 = 8 * 250 = 2000 // ... try { communicator.addListener(listener); communicator.send(unicastChannel, gateway, sendBuffer); int maxWaitTime = (1 << (attempt - 1)) * 250; // NOPMD T pcpResponse = null; long endTime = System.currentTimeMillis() + maxWaitTime; long waitTime; while ((waitTime = endTime - System.currentTimeMillis()) > 0L) { waitTime = Math.max(waitTime, 0L); // must be at least 0, probably should never happen ByteBuffer recvBuffer = recvBufferQueue.poll(waitTime, TimeUnit.MILLISECONDS); if (recvBuffer != null) { pcpResponse = creator.create(recvBuffer); if (pcpResponse != null) { break; } } } return pcpResponse; } finally { communicator.removeListener(listener); } }
From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java
/** * Sends an IQ packet to the Clearspace external component and returns the IQ packet * returned by CS or <tt>null</tt> if no answer was received before the specified * timeout.//from www. j a v a 2s . com * * @param packet IQ packet to send. * @param timeout milliseconds to wait before timing out. * @return IQ packet returned by Clearspace responsing the packet we sent. */ public IQ query(final IQ packet, int timeout) { // Complain if FROM is empty if (packet.getFrom() == null) { throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace"); } // If CS is not connected then return null if (clearspaces.isEmpty()) { return null; } // Set the target address to the IQ packet. Roate list so we distribute load String component; synchronized (clearspaces) { component = clearspaces.get(0); Collections.rotate(clearspaces, 1); } packet.setTo(component); final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8); final IQRouter router = XMPPServer.getInstance().getIQRouter(); router.addIQResultListener(packet.getID(), new IQResultListener() { public void receivedAnswer(IQ packet) { answer.offer(packet); } public void answerTimeout(String packetId) { Log.warn("No answer from Clearspace was received for IQ stanza: " + packet); } }); XMPPServer.getInstance().getIQRouter().route(packet); IQ reply = null; try { reply = answer.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Ignore } return reply; }
From source file:com.test.HibernateDerbyLockingTest.java
public void testJDBC() throws Exception { final DerbyTemplate template = new DerbyTemplate(); try {//from w w w . j av a 2 s. co m template.doWithStatement(new IStatementCallback() { public void execute(Statement statement) throws Exception { statement.execute( "CREATE TABLE TEST(\n" + "ID CHAR(36) NOT NULL,\n" + "NAME VARCHAR(255)\n" + ")"); } }); template.doWithStatement(new IStatementCallback() { public void execute(Statement statement) throws Exception { statement.execute("INSERT INTO TEST(ID, NAME) VALUES('12345', 'Bob')"); } }); final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(); ExecutorService executorService = Executors.newCachedThreadPool(); Future<?> submit = executorService.submit(new Callable<Object>() { public Object call() throws Exception { template.doWithStatement(new IStatementCallback() { public void execute(Statement statement) throws Exception { ResultSet resultSet = statement.executeQuery( "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rs"); while (resultSet.next()) { String id = resultSet.getString("ID"); String name = resultSet.getString("NAME"); } try { Thread.sleep(2000); } catch (Throwable t) { } System.out.println("one"); queue.add("one"); try { Thread.sleep(500); } catch (Throwable t) { } } }); return null; } }); Thread.sleep(500); Future<?> submit2 = executorService.submit(new Callable<Object>() { public Object call() throws Exception { template.doWithStatement(new IStatementCallback() { public void execute(Statement statement) throws Exception { ResultSet resultSet = statement.executeQuery( "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rr"); while (resultSet.next()) { String id = resultSet.getString("ID"); String name = resultSet.getString("NAME"); } queue.add("two"); System.out.println("two"); } }); return null; } }); submit.get(); submit2.get(); assertEquals("one", queue.poll(3, TimeUnit.SECONDS)); assertEquals("two", queue.poll(3, TimeUnit.SECONDS)); } finally { template.doWithStatement(new IStatementCallback() { public void execute(Statement statement) throws Exception { statement.execute("DROP TABLE TEST"); } }); } }
From source file:com.SecUpwN.AIMSICD.service.AimsicdService.java
/** * Updates Neighbouring Cell details/*from w w w . j av a 2s.c om*/ */ public List<Cell> updateNeighbouringCells() { List<Cell> neighboringCells = new ArrayList<>(); List<NeighboringCellInfo> neighboringCellInfo; neighboringCellInfo = tm.getNeighboringCellInfo(); if (neighboringCellInfo.size() == 0) { // try to poll the neighboring cells for a few seconds final LinkedBlockingQueue<NeighboringCellInfo> neighboringCellBlockingQueue = new LinkedBlockingQueue<>( 100); final PhoneStateListener listener = new PhoneStateListener() { private void handle() { List<NeighboringCellInfo> neighboringCellInfo; neighboringCellInfo = tm.getNeighboringCellInfo(); if (neighboringCellInfo.size() == 0) { return; } Log.i(TAG, "neighbouringCellInfo empty - event based polling succeeded!"); tm.listen(this, PhoneStateListener.LISTEN_NONE); neighboringCellBlockingQueue.addAll(neighboringCellInfo); } @Override public void onServiceStateChanged(ServiceState serviceState) { handle(); } @Override public void onDataConnectionStateChanged(int state) { handle(); } @Override public void onDataConnectionStateChanged(int state, int networkType) { handle(); } @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { handle(); } @Override public void onCellInfoChanged(List<CellInfo> cellInfo) { handle(); } }; Log.i(TAG, "neighbouringCellInfo empty - start polling"); //LISTEN_CELL_INFO added in API 17 if (Build.VERSION.SDK_INT > 16) { tm.listen(listener, PhoneStateListener.LISTEN_CELL_INFO | PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); } else { tm.listen(listener, PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); } for (int i = 0; i < 10 && neighboringCellInfo.size() == 0; i++) { try { Log.i(TAG, "neighbouringCellInfo empty - try " + i); NeighboringCellInfo info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS); if (info == null) { neighboringCellInfo = tm.getNeighboringCellInfo(); if (neighboringCellInfo.size() > 0) { Log.i(TAG, "neighbouringCellInfo empty - try " + i + " succeeded time based"); break; } else { continue; } } ArrayList<NeighboringCellInfo> cellInfoList = new ArrayList<NeighboringCellInfo>( neighboringCellBlockingQueue.size() + 1); while (info != null) { cellInfoList.add(info); info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS); } neighboringCellInfo = cellInfoList; } catch (InterruptedException e) { // normal } } } Log.i(TAG, "neighbouringCellInfo Size - " + neighboringCellInfo.size()); for (NeighboringCellInfo neighbourCell : neighboringCellInfo) { Log.i(TAG, "neighbouringCellInfo - CID:" + neighbourCell.getCid() + " LAC:" + neighbourCell.getLac() + " RSSI:" + neighbourCell.getRssi() + " PSC:" + neighbourCell.getPsc()); final Cell cell = new Cell(neighbourCell.getCid(), neighbourCell.getLac(), neighbourCell.getRssi(), neighbourCell.getPsc(), neighbourCell.getNetworkType(), false); neighboringCells.add(cell); } return neighboringCells; }