/** * After deserialization hook. Puts all vehicles on separate threads so everything will work as it * should * * @param in Fired on readobject * @throws IOException * @throws ClassNotFoundException */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); try { Thread.sleep(1000); } catch (InterruptedException e) { } for (int i = 0; i < getVehicles().size(); i++) { Thread t = new Thread(getVehicles().get(i)); t.start(); } for (int i = 0; i < getIntersections().size(); i++) { Thread t = new Thread(getIntersections().get(i)); t.start(); } Passenger p = passengers.poll(); while (p != null) { Thread t = new Thread(p); t.start(); p = passengers.poll(); } }
public int reverse(int x) { if (x == Integer.MIN_VALUE) return 0; int sign = (x >= 0 ? 1 : -1); x = Math.abs(x); java.util.concurrent.LinkedBlockingQueue<Integer> queue = new java.util.concurrent.LinkedBlockingQueue<>(); while (x != 0) { queue.offer(x % 10); x /= 10; } int res = 0; while (queue.peek() != null) { if (res > Integer.MAX_VALUE / 10) { return 0; } else if (res == Integer.MAX_VALUE / 10) { if (sign == 1 && queue.peek() <= 7) { res = res * 10 + queue.poll(); return res; } else if (sign == -1 && queue.peek() <= 8) { res = sign * res * 10 + sign * queue.poll(); return res; } } res = res * 10 + queue.poll(); } return sign * res; }
@Override public synchronized int read(byte[] b, int off, int len) throws IOException { int need = len; if (need <= 0) { return need; } do { if (currentRead != null) { int r = currentRead.read(b, off, need); if (r > 0) { off += r; need -= r; } } if (need == 0) { return len; } byte[] buf = null; try { buf = reads.poll(READTIMEOUT, TimeUnit.SECONDS); if (buf == null || buf == closedMark) { return -1; } } catch (InterruptedException e) { throw new IOException(e); } currentRead = new ByteArrayInputStream(buf); } while (need > 0); return len; }
@Override public ErisMessage receive(long timeout) throws org.eris.messaging.TransportException, org.eris.messaging.ReceiverException, org.eris.messaging.TimeoutException { checkClosed(); if (_creditMode == CreditMode.EXPLICT && _capacity == 0) { throw new org.eris.messaging.ReceiverException( "Since CreditMode is EXPLICIT, you need to explicity set the capacity before calling receive"); } issuePreReceiveCredit(); ErisMessage msg = null; try { if (timeout == 0) { msg = _queue.take(); } else { msg = _queue.poll(timeout, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { checkClosed(); } if (msg != null) { issuePostReceiveCredit(); return msg; } else { checkClosed(); if (timeout == 0) { throw new org.eris.messaging.ReceiverException("Receive operation was interrupted"); } else { throw new org.eris.messaging.TimeoutException( "Timeout waiting for message to be available"); } } }
public Tweet getNextTweet() { try { return tweets.poll(200, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return null; } }
public static void event(Call call, String event, Object data) { if (call == null) { Log.i(TAG, "Non-call EVENT: %s, %s", event, data); return; } synchronized (mCallEventRecords) { if (!mCallEventRecordMap.containsKey(call)) { // First remove the oldest entry if no new ones exist. if (mCallEventRecords.remainingCapacity() == 0) { CallEventRecord record = mCallEventRecords.poll(); if (record != null) { mCallEventRecordMap.remove(record.getCall()); } } // Now add a new entry CallEventRecord newRecord = new CallEventRecord(call); mCallEventRecords.add(newRecord); mCallEventRecordMap.put(call, newRecord); } CallEventRecord record = mCallEventRecordMap.get(call); record.addEvent(event, data); } }
/* * (non-Javadoc) * * @see org.mixare.mgr.downloader.DownloadManager#run() */ public void run() { ManagedDownloadRequest mRequest; DownloadResult result = null; stop = false; while (!stop) { state = DownloadManagerState.OnLine; // Wait for proceed while (!stop) { try { mRequest = todoList.poll(10, TimeUnit.SECONDS); if (mRequest == null) { ctx.getActualMixView().refresh(); return; } state = DownloadManagerState.Downloading; result = processRequest(mRequest); } catch (InterruptedException e) { result = new DownloadResult(); result.setError(e, null); } catch (Exception ex) { // do nothing terminating } if (result != null) doneList.put(result.getIdOfDownloadRequest(), result); state = DownloadManagerState.OnLine; } } state = DownloadManagerState.OffLine; }
@Test @Transactional @Rollback public void verify() throws Exception { final LinkedBlockingQueue<HttpRequest> requests = new LinkedBlockingQueue<HttpRequest>(); server.register( "/*", new HttpRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { requests.add(request); response.setEntity( new StringEntity( getQueryParamValue(request.getRequestLine().getUri(), "hub.challenge"))); } }); subscriber.verify(SubscriptionMode.SUBSCRIBE); Assert.assertEquals(1, requests.size()); HttpRequest actualRequest = requests.poll(); String requestUri = actualRequest.getRequestLine().getUri(); Assert.assertEquals("subscribe", getQueryParamValue(requestUri, "hub.mode")); Assert.assertEquals( subscriber.getTopic().toString(), URLDecoder.decode(getQueryParamValue(requestUri, "hub.topic"), "UTF-8")); Assert.assertNotNull(getQueryParamValue(requestUri, "hub.challenge")); Assert.assertEquals("123", getQueryParamValue(requestUri, "hub.lease_seconds")); Assert.assertEquals( subscriber.getVerifyToken(), getQueryParamValue(requestUri, "hub.verify_token")); }
@Override public void nextTuple() { // emit tweets Status status = statuses.poll(); if (status == null) Utils.sleep(1000); else { ResponseList<User> followers; ResponseList<User> friends; try { Thread.sleep(6000); followers = twitter.getFollowersList(status.getUser().getScreenName(), -1); Thread.sleep(6000); friends = twitter.getFriendsList(status.getUser().getScreenName(), -1); if (!followers.isEmpty() && !friends.isEmpty()) { spoutOutputCollector.emit(new Values(status, followers, friends)); } // followers.clear(); // friends.clear(); } catch (TwitterException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
@Override public void run() { timer.scheduleAtFixedRate( new TimerTask() { @Override public void run() { for (String ip : ips) { int idx = Math.abs(ip.hashCode() % ip_cnts.length); if (ip_cnts[idx] > DISC_THRESHOLD) { log.warning("Many disconnects for IP: " + ip + " - " + ip_cnts[idx]); } ip_cnts[idx] = 0; } } }, CLEANUP_RATE, CLEANUP_RATE); while (!stopped) { try { String ip = queue.poll(10, TimeUnit.SECONDS); if (ip != null) { int idx = Math.abs(ip.hashCode()) % ip_cnts.length; ++ip_cnts[idx]; if (ips.size() < MAX_SIZE) { ips.add(ip); } } } catch (Exception e) { log.warning("Error processing queue: " + e); } } timer.cancel(); }
@Override public IQ query(Component component, IQ packet, long timeout) throws ComponentException { final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<>(8); XMPPServer.getInstance() .getIQRouter() .addIQResultListener( packet.getID(), new IQResultListener() { @Override public void receivedAnswer(IQ packet) { answer.offer(packet); } @Override public void answerTimeout(String packetId) { Log.warn( "An answer to a previously sent IQ stanza was never received. Packet id: " + packetId); } }); sendPacket(component, packet); IQ reply = null; try { reply = answer.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // Ignore } return reply; }
/** * Sends messages from the queue. While the queue is not empty, polls message from it and sends it * to the remote peer. If the queue is empty for more than 2 minutes, a keep-alive message is sent * and the DownloadTask is advertised */ public void run() { Message out = null; byte[] keep = new Message_PP(PeerProtocol.KEEP_ALIVE).generate(); try { while (this.run) { if (this.outgoingMessage != null && this.os != null) out = outgoingMessage.poll(120000, TimeUnit.MILLISECONDS); if (out != null) { os.write(out.generate()); this.lmst = System.currentTimeMillis(); out = null; } else if (this.run) { os.write(keep); this.fireKeepAliveSent(); } } } catch (InterruptedException ie) { } catch (IOException ioe) { this.fireConnectionClosed(); } catch (Exception e) { this.fireConnectionClosed(); } if (this.outgoingMessage != null) this.outgoingMessage.clear(); this.outgoingMessage = null; try { this.os.close(); this.os = null; this.notify(); } catch (Exception e) { } }
/** {@inheritDoc} */ public ScheduledTask getNextTask(boolean wait) throws InterruptedException { ScheduledTask task = queue.poll(); if ((task != null) || (!wait)) { return task; } return queue.take(); }
public void run() { Thread.currentThread().setName("Queue-" + localStats.name); logger.info("Processing queue starting up for " + localStats.name); while (!shutdown) { TrackedRequest req = null; try { req = inQueue.poll(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { continue; } if (req == null) { continue; } synchronized (stats) { localStats.processedEvents++; } try { processor.process(req); } catch (Exception e) { synchronized (stats) { localStats.processFailedEvents++; } logger.info("Processing error", e); } } logger.info("Tracker thread for " + localStats.name + " shutting down"); try { processor.shutdown(); } catch (Exception e) { logger.error("Failed to close last file", e); } }
@Override public void postFrame(double timePerFrame) { super.postFrame(timePerFrame); while (!nodesToAddPostFrame.isEmpty()) { getGraphics3DAdapter().getRenderer().getZUpNode().attachChild(nodesToAddPostFrame.poll()); } }
@Override public Message poll(TimeProperty timeout) { try { return queue.poll(timeout.getTime(), timeout.getUnit()); } catch (InterruptedException e) { return null; } }
@Override public V take(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { V v = queue.poll(timeout, unit); if (v == null) { throw new TimeoutException(); } return v; }
@Override public void put(V value) { if (value == null) { throw new NullPointerException(); } while (!queue.offer(value)) { queue.poll(); } }
public void runMatcher() { System.out.println("Matcher => runMatcher() metodu..."); if (ObjectiveQ == null) System.out.println("incomingQ null..."); if (ObjectiveQ.isEmpty()) { System.out.println("incomingQ bos..."); } Objective incomingObjective = (Objective) ObjectiveQ.poll(); Match(incomingObjective); }
@Override public List<Message> removeAll() { List<Message> messages = new ArrayList<>(); Message m; while ((m = queue.poll()) != null) { messages.add(m); } return messages; }
@Override public void nextTuple() { Status ret = queue.poll(); if (ret == null) { Utils.sleep(50); } else { _collector.emit(new Values(ret)); } }
/** Pull a cached instance */ public static ReusableGZIPInputStream acquire() { ReusableGZIPInputStream rv = null; // Apache Harmony 5.0M13 Deflater doesn't work after reset() if (ENABLE_CACHING) rv = _available.poll(); if (rv == null) { rv = new ReusableGZIPInputStream(); } return rv; }
private void process_removals() throws Exception { FileChange change = removalsToProcess.poll(1, TimeUnit.SECONDS); if (change == null) { return; } logger.fine("process removals: " + change.tree); String comp_path = change.tree.thisFile.getAbsolutePath(); List<DownloadManager> toRemove = new ArrayList<DownloadManager>(); GlobalManager gm = AzureusCoreImpl.getSingleton().getGlobalManager(); for (DownloadManager dm : (List<DownloadManager>) gm.getDownloadManagers()) { if (dm.getSaveLocation().getAbsolutePath().startsWith(comp_path)) { logger.fine( "saveLocation.startsWith() delete of: " + dm.getSaveLocation().getAbsolutePath() + " / " + comp_path); toRemove.add(dm); } else if (comp_path.startsWith(dm.getSaveLocation().getAbsolutePath())) // deleted // a // file // in // the // torrent // directory // we // created, // need // to // remove // (and // possibly // rehash) { logger.fine( "comp_path.startsWith delete of: " + dm.getSaveLocation().getAbsolutePath() + " / " + comp_path); toRemove.add(dm); } } for (DownloadManager dm : toRemove) { logger.info("delete causes removal of: " + dm.getTorrentFileName()); try { gm.removeDownloadManager(dm, true, false); // remove torrent // file (which we // created), but not // data } catch (Exception e) { e.printStackTrace(); } } }
@Override public T borrowObject() throws InterruptedException, PoolException { T object = linkQueue.poll(2000, TimeUnit.MILLISECONDS); if (object == null) { throw new PoolException(); } poolSize.getAndDecrement(); return object; }
/** * Returns the next available packet. The method call will block (not return) until a packet is * available or the <tt>timeout</tt> has elapased. If the timeout elapses without a result (or the * thread is interrupted), <tt>null</tt> will be returned. * * @param timeout the amount of time in milliseconds to wait for the next packet. * @throws IllegalStateException if this collector is canceled * @return the next available packet. */ public Packet nextResult(long timeout) { if (canceled && resultQueue.isEmpty()) throw new IllegalStateException("Canceled packet collector"); try { return resultQueue.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { // Ignore return null; } }
public static void main(String[] args) { LinkedBlockingQueue<BufferedImage> imgQueue = new LinkedBlockingQueue<>(16); Queue<Task> tasksQueue = new LinkedList<>(); new TaskListInitialize(tasksQueue); int activeDownloadThreads = 0, activeResizeThreads = 0; // downloaded and resized pictures adding to the queues only at the end // that's why we need counters to control amount of active threads long start_time = System.currentTimeMillis(); while (true) { try { if ((activeDownloadThreads != 16) && !tasksQueue.isEmpty()) { // if we have a free threads for download - fill it Thread downloadThread = new Thread(new DownloadThread(tasksQueue.poll(), imgQueue)); downloadThread.start(); activeDownloadThreads++; } else if (activeResizeThreads != 4) { // if we have a free resize threads - fill it too BufferedImage img = imgQueue.poll(2, TimeUnit.SECONDS); // wait while first image will be download activeDownloadThreads--; if (img != null) { Thread resizeThread = new Thread(new ResizeThread(img)); resizeThread.start(); ++activeResizeThreads; } else break; // if any pictures wasn't added during 2second - close the program } else { resizeThreadQueue.poll( 2, TimeUnit .SECONDS); // if all threads is active, wait while any resize thread becames free activeResizeThreads--; } } catch (InterruptedException e) { } } long end_time = System.currentTimeMillis(); System.out.println((end_time - start_time) / 1000.0); }
@Override public void run() { while (!stop) { // 业务逻辑 try { // 这里做流量控制 TpsTool.limitTPS(); // 取包发送 APackage pack = this.doSubmit(); if (pack == null) { pack = buffer.poll(); } if (pack == null) { // 确认是否需要发送链路检测包 long curTime = System.currentTimeMillis(); if (curTime > (lastActiveTime + timeout)) { if (channel.isLogin()) { // 链路已经空闲超过60s,且连接还未断开,需要发送UnbindMessage包 log.info("链路空闲超过" + timeout + "ms,发送UnbindMessage包断开连接"); channel.unbind(); } } } if (pack == null) { continue; } // 设置发送时间 lastActiveTime = System.currentTimeMillis(); try { boolean flag = sendPacket(pack); if (!flag) { buffer.offer(pack); } } catch (IOException ex) { // 发送失败重发 log.error(null, ex); if (pack.getTryTimes() < retryTimes) { buffer.offer(pack); } else { // 记录丢失的包到文件中 discard.info( "丢失包,重试多次失败" + pack.getHead().getCommandIdString() + ",字节码:" + Hex.rhex(pack.getBytes())); } } } catch (Exception ex) { log.error(null, ex); // 发生异常,强制关闭连接 channel.close(); } } }
public void flush() throws FileNotFoundException { gpsiIOElement element; File file; while (!stream.isEmpty()) { element = stream.poll(); file = new File(root + element.path); if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); element.setPath(root + element.path); element.write(); } }
protected Request obtain(final int request, final int arg1, final Object arg2) { Request req = mRequestPool.poll(); if (req != null) { req.request = request; req.arg1 = arg1; req.arg2 = arg2; } else { req = new Request(request, arg1, arg2); } return req; }
private WatchedEvent getEvent(int numTries) throws InterruptedException { WatchedEvent event = null; for (int i = 0; i < numTries; i++) { System.out.println("i = " + i); event = events.poll(10, TimeUnit.SECONDS); if (event != null) { break; } Thread.sleep(5000); } return event; }