/** Selects on sockets and informs their Communicator when there is something to do. */ public void communicate(int timeout) { try { selector.select(timeout); } catch (IOException e) { // Not really sure why/when this happens yet return; } Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); keys.remove(); if (!key.isValid()) continue; // WHY Communicator communicator = (Communicator) key.attachment(); if (key.isReadable()) communicator.onReadable(); if (key.isWritable()) communicator.onWritable(); if (key.isAcceptable()) communicator.onAcceptable(); } // Go through the queue and handle each communicator while (!queue.isEmpty()) { Communicator c = queue.poll(); c.onMemo(); } }
public void initArchitecture() { this.engine = VizController.getInstance().getEngine(); this.drawable = VizController.getInstance().getDrawable(); this.limits = VizController.getInstance().getLimits(); this.vizController = VizController.getInstance(); leaves = new ParamAVLTree<Octant>( new AVLItemAccessor<Octant>() { public int getNumber(Octant item) { return item.getNumber(); } }); visibleLeaves = new ArrayList<Octant>(); selectedLeaves = new ArrayList<Octant>(); iteratorQueue = new ConcurrentLinkedQueue<OctreeIterator>(); iteratorQueue.add(new OctreeIterator()); iteratorQueue.add(new OctreeIterator()); iteratorQueue.add(new OctreeIterator()); iteratorQueue.add(new OctreeIterator()); float dis = size / (float) Math.pow(2, this.maxDepth + 1); root = new Octant(this, 0, dis, dis, dis, size); }
/** Transport connected. {@link IOTransport} calls this when a connection is established. */ 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; } }
void sendPartitionInfos() { // check if the ExecutionVertex has already been archived and thus cleared the // partial partition infos queue if (partialInputChannelDeploymentDescriptors != null && !partialInputChannelDeploymentDescriptors.isEmpty()) { PartialInputChannelDeploymentDescriptor partialInputChannelDeploymentDescriptor; List<IntermediateDataSetID> resultIDs = new ArrayList<IntermediateDataSetID>(); List<InputChannelDeploymentDescriptor> inputChannelDeploymentDescriptors = new ArrayList<InputChannelDeploymentDescriptor>(); while ((partialInputChannelDeploymentDescriptor = partialInputChannelDeploymentDescriptors.poll()) != null) { resultIDs.add(partialInputChannelDeploymentDescriptor.getResultId()); inputChannelDeploymentDescriptors.add( partialInputChannelDeploymentDescriptor.createInputChannelDeploymentDescriptor(this)); } UpdatePartitionInfo updateTaskMessage = createUpdateTaskMultiplePartitionInfos( attemptId, resultIDs, inputChannelDeploymentDescriptors); sendUpdatePartitionInfoRpcCall(assignedResource, updateTaskMessage); } }
public void updateMessages() { synchronized (this.messageList) { if (getView() == null) { return; } final ConversationActivity activity = (ConversationActivity) getActivity(); if (this.conversation != null) { updateSnackBar(this.conversation); conversation.populateWithMessages(ConversationFragment.this.messageList); for (final Message message : this.messageList) { if (message.getEncryption() == Message.ENCRYPTION_PGP && (message.getStatus() == Message.STATUS_RECEIVED || message.getStatus() >= Message.STATUS_SEND) && message.getTransferable() == null) { if (!mEncryptedMessages.contains(message)) { mEncryptedMessages.add(message); } } } decryptNext(); updateStatusMessages(); this.messageListAdapter.notifyDataSetChanged(); updateChatMsgHint(); if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) { activity.sendReadMarkerIfNecessary(conversation); } this.updateSendButton(); } } }
/** 停止所有任务 */ public void stopAllTask() { // 从下载队列移除 for (Map.Entry<String, DownloadHttpTask> entry : mDownloadingTaskMap.entrySet()) { DownloadHttpTask task = entry.getValue(); task.setInterrupt(true); } mDownloadingTaskMap.clear(); Iterator<DownloadInfo> downloadingIt = mDownloadingTasks.iterator(); while (downloadingIt.hasNext()) { DownloadInfo b = downloadingIt.next(); b.setState(DownloadInfo.PAUSE); downloadingIt.remove(); mPausingTasks.add(b); // 放入暂停队列 } mDownloadingTasks.clear(); // 从等待队列移除 Iterator<DownloadInfo> waitIt = mWaitTasks.iterator(); while (waitIt.hasNext()) { DownloadInfo b = waitIt.next(); b.setState(DownloadInfo.PAUSE); waitIt.remove(); mPausingTasks.add(b); // 放入暂停队列 break; } mWaitTasks.clear(); }
public static void main(String[] args) { Thread[] threads = new Thread[LIST_SIZE]; ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); for (int i = 0; i < LIST_SIZE; i++) { threads[i] = new Thread(new AddTask(queue)); threads[i].start(); } for (int i = 0; i < LIST_SIZE; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("AddTAsks has add"); for (int i = 0; i < LIST_SIZE; i++) { threads[i] = new Thread(new PollTask(queue)); threads[i].start(); } for (int i = 0; i < LIST_SIZE; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("PollTasks has add"); System.out.println("The size of list is " + queue.size()); }
/** Flush any caches to the database TODO */ private void _flush() { // periodically update protections in the database if a non-critical change was made if (protectionUpdateQueue.size() > 0) { Connection connection = lwc.getPhysicalDatabase().getConnection(); Protection protection = null; try { connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } /* * Loop through */ while ((protection = protectionUpdateQueue.poll()) != null) { protection.saveNow(); } /* * Commit */ try { connection.commit(); connection.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } flush = false; lastUpdate = System.currentTimeMillis(); }
protected ReceiveStatus fetch( List<? super M> list, Duration timeoutDuration, FunctionThrowsExceptions<java.util.Queue<Message>, Boolean> fetcher) throws DataStreamInfrastructureException, InterruptedException { ConcurrentLinkedQueue<Message> fetched = new ConcurrentLinkedQueue<>(); boolean outOfRangeReached = false; try { outOfRangeReached = fetcher.apply(fetched); } catch (TimeoutException | UncheckedTimeoutException e) { // do nothing } catch (InterruptedException e) { throw e; } catch (JMSException e) { throw new DataStreamInfrastructureException(e); } catch (Exception e) { throw Throwables.propagate(e); } int fetchedCount = fetched.size(); // the working thread may still being adding new element to fetched if (fetchedCount > 0) { Message msg = null; while (fetchedCount-- > 0) { msg = fetched.remove(); list.add(convert(msg)); } return new SimpleReceiveStatus(position(msg), enqueuedTime(msg), outOfRangeReached); } else { return new SimpleReceiveStatus(null, null, outOfRangeReached); } }
/** Called from VideoEngine */ public void hleGeListSyncDone(PspGeList list) { if (log.isDebugEnabled()) { String msg = "hleGeListSyncDone list " + list; if (list.isDone()) { msg += ", done"; } else { msg += ", NOT done"; } if (list.blockedThreadIds.size() > 0 && list.status != PSP_GE_LIST_END_REACHED) { msg += ", waking thread"; for (int threadId : list.blockedThreadIds) { msg += " " + Integer.toHexString(threadId); } } log.debug(msg); } synchronized (this) { if (list.blockedThreadIds.size() > 0 && list.status != PSP_GE_LIST_END_REACHED) { // things might go wrong if the thread already exists in the queue deferredThreadWakeupQueue.addAll(list.blockedThreadIds); } if (list.isDone()) { listFreeQueue.add(list); } } }
@Override public void run() { if (operatori == null) { operatori = new Operators(); } Evaluator evaluator = ((IEvaluatorProvider) Thread.currentThread()).getEvaluator(); Integer brojZaNapraviti = null; while (true) { brojZaNapraviti = ulazniRedTotalParalel.poll(); if (brojZaNapraviti != null) { for (int i = 0; i < brojZaNapraviti; i++) { Solution p1 = operatori.findParent(populacija, Constants.tournament); Solution p2 = operatori.findParent(populacija, Constants.tournament); Solution child = operatori.createChild(p1, p2); evaluator.evaluate(child); izlazniRedTotalParalel.add(child); } } else { break; } } }
/** * Removes any tasks waiting to be run. Will not interrupt any tasks currently running if {@link * #tick(ExceptionHandlerInterface)} is being called. But will avoid additional tasks from being * run on the current {@link #tick(ExceptionHandlerInterface)} call. * * <p>If tasks are added concurrently during this invocation they may or may not be removed. * * @return List of runnables which were waiting in the task queue to be executed (and were now * removed) */ public List<Runnable> clearTasks() { List<TaskContainer> containers; synchronized (scheduledQueue.getModificationLock()) { containers = new ArrayList<TaskContainer>(executeQueue.size() + scheduledQueue.size()); Iterator<? extends TaskContainer> it = executeQueue.iterator(); while (it.hasNext()) { TaskContainer tc = it.next(); /* we must use executeQueue.remove(Object) instead of it.remove() * This is to assure it is atomically removed (without executing) */ if (!tc.running && executeQueue.remove(tc)) { int index = ListUtils.getInsertionEndIndex(containers, tc, true); containers.add(index, tc); } } it = scheduledQueue.iterator(); while (it.hasNext()) { TaskContainer tc = it.next(); if (!tc.running) { int index = ListUtils.getInsertionEndIndex(containers, tc, true); containers.add(index, tc); } } scheduledQueue.clear(); } return ContainerHelper.getContainedRunnables(containers); }
public static void release(SessionRemote sr) { if (sr == null || sr.isClosed()) return; ConcurrentLinkedQueue<SessionRemote> queue = getQueue(sr.getURL()); if (queue.size() > corePoolSize) sr.close(); else queue.offer(sr); }
/** * Returns an instance of a specific checksum algorithm for caching. * * @param instance of the algorithm */ public void returnAlgorithm(ChecksumAlgorithm algorithm) { ConcurrentLinkedQueue<ChecksumAlgorithm> cache = pool.get(algorithm.getName()); if (cache.size() < MAX_CACHE_SIZE) { algorithm.reset(); cache.add(algorithm); } }
/** * Releases any resources held by the writer. * * @param shutdownWrapped If the wrapped writer should be closed as well. */ public void shutdown(boolean shutdownWrapped) { stopRequested.set(true); // Wait for publisher thread to terminate while (writerThread != null && writerThread.isAlive()) { try { // Interrupt the thread if its blocking writerThread.interrupt(); writerThread.join(); } catch (InterruptedException ex) { // Ignore; we gotta wait.. } } // The writer writerThread SHOULD have drained the queue. // If not, handle outstanding requests ourselves, // and push them to the writer. while (!queue.isEmpty()) { String message = queue.poll(); writer.writeRecord(message); } // Shutdown the wrapped writer. if (shutdownWrapped && writer != null) writer.shutdown(); DirectoryServer.deregisterShutdownListener(this); }
/** {@inheritDoc} */ public void destroy() { started.set(false); destroyed.set(true); releaseExternalResources(); if (notifierFuture != null) { notifierFuture.cancel(true); } if (asyncWriteFuture != null) { asyncWriteFuture.cancel(true); } if (bc != null) { bc.destroy(); } if (broadcasterCache != null) { broadcasterCache.stop(); } resources.clear(); broadcastOnResume.clear(); messages.clear(); asyncWriteQueue.clear(); delayedBroadcast.clear(); broadcasterCache = null; if (BroadcasterFactory.getDefault() != null) { BroadcasterFactory.getDefault().remove(this, name); } if (currentLifecycleTask != null) { currentLifecycleTask.cancel(true); } }
public void checkqueue() { if (!ismoving && !movequeue.isEmpty()) { ismoving = true; UI.instance.mainview.moveto = movequeue.poll(); movequeue.remove(0); } }
public String getNextInboundMessage() { String result = null; if (!inboundCommandQueue.isEmpty()) { result = inboundCommandQueue.poll(); } return result; }
/** * * 解析从服务器收到的包,切割完整包,并返回半包 * * @param unHandledPkg 从socket收到的数据包 * @param parser 不同的协议,传递不同的包内容解析器 * @return 如果收到的包是一个或者多个完整包,那么返回0长度字节数组 如果收到的包是1个半或者N个半数据包,那么截取一个或N个完整包,并把剩余的部分返回 */ private final byte[] handlePackage(byte[] unHandledPkg, IPackageContenParser parser) { /** 调用一次read,从Server收到的数据包(可能是半包、1个包、1.x、2.x....) */ int pkgLen = unHandledPkg.length; /** 一个完整数据包的长度 */ int completePkgLen = parser.getCompletePackageLength(unHandledPkg); if (completePkgLen > pkgLen) { /** 当前收到的数据不到一个完整包,则直接返回,等待下一个包 */ return unHandledPkg; } else if (completePkgLen == pkgLen) { /** 一个完整包,则直接丢到已处理队列 */ handledQueue.offer(unHandledPkg); return EmptyContainer.EMPTY_BYTE_ARRAY; } else { /** 有多个包,那么就递归解析, */ byte[] onePkg = parser.getCompletePackage(unHandledPkg); handledQueue.offer(onePkg); /** 截取除完整包后的剩余部分 */ byte[] remain = PackageTools.getSubBytes(unHandledPkg, onePkg.length, pkgLen - onePkg.length); return handlePackage(remain, parser); } }
protected void simulateOptions(Game game, Ability previousActions) { allActions.add(previousActions); List<Ability> playables = game.getPlayer(playerId).getPlayable(game, isSimulatedPlayer); for (Ability ability : playables) { List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game); if (options.isEmpty()) { if (ability.getManaCosts().getVariableCosts().size() > 0) { simulateVariableCosts(ability, game); } else { allActions.add(ability); } // simulateAction(game, previousActions, ability); } else { // ExecutorService simulationExecutor = Executors.newFixedThreadPool(4); for (Ability option : options) { if (ability.getManaCosts().getVariableCosts().size() > 0) { simulateVariableCosts(option, game); } else { allActions.add(option); } // SimulationWorker worker = new SimulationWorker(game, this, // previousActions, option); // simulationExecutor.submit(worker); } // simulationExecutor.shutdown(); // while(!simulationExecutor.isTerminated()) {} } } }
public long getNextSequence(TypeDescriptor typeDescriptor, Session session) { // check if there is an id in the cache ConcurrentLinkedQueue cachedIds = (ConcurrentLinkedQueue) this.typeDescriptorToIdCache.get(typeDescriptor); if (null == cachedIds) { typeDescriptorToIdCache.putIfAbsent(typeDescriptor, new ConcurrentLinkedQueue()); cachedIds = (ConcurrentLinkedQueue) this.typeDescriptorToIdCache.get(typeDescriptor); } Number cachedId = (Number) cachedIds.poll(); if (cachedId == null) { synchronized (cachedIds) { cachedId = (Number) cachedIds.poll(); if (cachedId == null) { List newIds = this.getNextSequenceImpl(typeDescriptor, session); Assert.condition(0 < newIds.size()); // reserve first for own use cachedId = (Number) newIds.remove(0); cachedIds.addAll(newIds); } } } if (trace.isDebugEnabled()) { trace.debug("returning unique ID: " + cachedId.longValue()); } return cachedId.longValue(); }
@Override public boolean offer(E e) { if (queue.size() > capacity) { queue.poll(); } queue.offer(e); return true; }
private void cacheNotification(ApnsNotification notification) { cachedNotifications.add(notification); while (cachedNotifications.size() > cacheLength) { cachedNotifications.poll(); logger.debug("Removing notification from cache " + notification); UILogger.getInstance().add("Removing notification from cache " + notification); } }
public void restore(TileGenerator tileGenerator) { if (mPool.size() < mMaxSize && mPool.offer(tileGenerator)) { return; } // pool is too big or returning to pool failed, so just try to clean // up. tileGenerator.cleanUp(); }
public synchronized boolean add(E e) { counter++; if (counter == 16) { queue.remove(); counter--; } return queue.add(e); }
/** Returns true if the specified plugin location is an inline location. */ @SuppressWarnings("unchecked") public boolean isInlinePluginLocation(File pluginLocation) { if (pluginLocation == null) return false; getPluginDirectories(); // initialize the cache ConcurrentLinkedQueue<File> locations = (ConcurrentLinkedQueue<File>) cache.get(KEY_INLINE_PLUGIN_LOCATIONS); return locations != null && locations.contains(pluginLocation); }
public TrPeerInfo getPeerForAssimilation() { if (peers.isEmpty()) { // We need to use a public peer final ArrayList<File> publicNodeIdFiles = node.getPublicNodeIdFiles(); final File pubPeerFile = publicNodeIdFiles.get(TrUtils.rand.nextInt(publicNodeIdFiles.size())); final TrPeerInfo pnii = Persistence.loadReadOnly(TrPeerInfo.class, pubPeerFile); return pnii; } else { /** * Here we use a trick to pick peers in proportion to the probability that they will be the * fastest peer */ TrPeerInfo bestPeer = null; double bestTimeEstimate = Double.MAX_VALUE; final LinearStat globalSuccessTime = new LinearStat(Integer.MAX_VALUE); globalSuccessTime.sample(1000); globalSuccessTime.sample(2000); for (final TrPeerInfo ifo : peers.values()) { if (ifo.assimilation.successTimeSqrt.total > 0) { globalSuccessTime.sample(ifo.assimilation.successTimeSqrt.mean()); } } for (final Entry<PhysicalNetworkLocation, TrPeerInfo> e : peers.entrySet()) { final double guessFailureProb = e.getValue().assimilation.successRate.getBetaRandom(); double guessSuccessTime; // If we don't have at least 2 samples, use our global success // time if (e.getValue().assimilation.successTimeSqrt.total > 2) { final double guessSuccessTimeSqrt = e.getValue().assimilation.successTimeSqrt.getNormalRandom(); guessSuccessTime = guessSuccessTimeSqrt * guessSuccessTimeSqrt; } else { final double guessSuccessTimeSqrt = globalSuccessTime.getNormalRandom(); guessSuccessTime = guessSuccessTimeSqrt * guessSuccessTimeSqrt; } double timeEstimate = guessSuccessTime + AssimilateSessionImpl.RELAY_ASSIMILATION_TIMEOUT_SECONDS * 1000l * guessFailureProb; if (lastAttemptedRelays.contains(e.getValue())) { timeEstimate *= RECENTLY_ATTEMPTED_PENALTY; } if (timeEstimate < bestTimeEstimate) { bestPeer = e.getValue(); bestTimeEstimate = timeEstimate; } } lastAttemptedRelays.add(bestPeer); while (lastAttemptedRelays.size() > 5) { lastAttemptedRelays.poll(); } return bestPeer; } }
protected void sendUpdates() { // get the current version int currentVersion = version.get(); // boolean persist = isPersistentObject(); // get read-only version of events ConcurrentLinkedQueue<ISharedObjectEvent> events = new ConcurrentLinkedQueue<ISharedObjectEvent>(ownerMessage.getEvents()); // clear out previous events ownerMessage.getEvents().clear(); // if (!events.isEmpty()) { // Send update to "owner" of this update request SharedObjectMessage syncOwner = new SharedObjectMessage(null, name, currentVersion, persist); syncOwner.addEvents(events); if (source != null) { // Only send updates when issued through RTMP request Channel channel = ((RTMPConnection) source).getChannel((byte) 3); if (channel != null) { // ownerMessage.acquire(); channel.write(syncOwner); log.debug("Owner: {}", channel); } else { log.warn("No channel found for owner changes!?"); } } } // clear owner events events.clear(); // get read-only version of sync events events.addAll(syncEvents); // clear out previous events syncEvents.clear(); if (!events.isEmpty()) { // Synchronize updates with the current listeners of this shared for (IEventListener listener : currentListeners) { if (listener == source) { // Don't re-send update to active client log.debug("Skipped {}", source); continue; } if (!(listener instanceof RTMPConnection)) { log.warn("Can't send sync message to unknown connection {}", listener); continue; } // Create a new sync message for every client to avoid // concurrent access through multiple threads // TODO: perhaps we could cache the generated message SharedObjectMessage syncMessage = new SharedObjectMessage(null, name, currentVersion, persist); syncMessage.addEvents(events); Channel channel = ((RTMPConnection) listener).getChannel((byte) 3); log.debug("Send to {}", channel); channel.write(syncMessage); } } }
public void addSavingOperation(WiFiApConfig... config) { saveOperations.addAll(Arrays.asList(config)); Timber.d("Save operations: %d (after ADD)", saveOperations.size()); Intents.callIntent(context, Intents.PROXY_REFRESH_UI); Intent serviceIntent = new Intent(context, SaveWifiNetworkService.class); context.startService(serviceIntent); }
public void run() { // while (queue.size()>0) { while (!queue .isEmpty()) { // 这里不要用size()==0会非常耗时 会遍历一遍整个队列 而isEmpty()则是看看队列对头是否为空 要是为空则整个队列的大小就是0 // while(queue.size()!=0){ System.out.println(queue.poll()); } latch.countDown(); }