Java Code Examples for java.util.Iterator#remove()

The following examples show how to use java.util.Iterator#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActivityUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 结束所有 Activity
 * @return {@link ActivityUtils}
 */
public ActivityUtils finishAllActivity() {
    synchronized (mActivityStacks) {
        // 保存新的堆栈, 防止出现同步问题
        Stack<Activity> stack = new Stack<>();
        stack.addAll(mActivityStacks);
        // 清空全部, 便于后续操作处理
        mActivityStacks.clear();
        // 进行遍历移除
        Iterator<Activity> iterator = stack.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
                // 删除对应的 Item
                iterator.remove();
            }
        }
        // 移除数据, 并且清空内存
        stack.clear();
        stack = null;
    }
    return this;
}
 
Example 2
Source File: V7ProducerList.java    From coding-snippets with MIT License 6 votes vote down vote up
@Override
	public void flush() {
		// TODO Auto-generated method stub
		//解决list中剩余没有写入的
//		System.out.println(Thread.currentThread().getName()+" 开始flush");
		String key = null;
		Entry<String, Integer> e = null;
		Iterator<Entry<String, Integer>> it = null;
		while(storeOff.size() > 0){
			it = storeOff.entrySet().iterator();
			while(it.hasNext()){
				e = it.next();
				key = e.getKey();
				//能把值更改为true的才获得mapBuffer,并开始写。否则等待下次send
				if(isReading.get(key).compareAndSet(false, true)){
					mapBuffer = allMapBuffer.get(key);
					sendList(data.get(key).get(producerId), e.getValue());
					isReading.get(key).set(false);
					it.remove();
				}
			}
		}
	}
 
Example 3
Source File: RequestBarrier.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
/**
 * 清理所有超时的请求
 */
public void evict() {
    Iterator<Map.Entry<Integer, ResponseFuture>> iterator = futures.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<Integer, ResponseFuture> entry = iterator.next();
        ResponseFuture future = entry.getValue();
        long timeout = future.getBeginTime() + future.getTimeout() + config.getClearInterval();

        if (timeout <= SystemClock.now() && future.getResponse() == null) {
            iterator.remove();
            if (future.release()) {
                try {
                    future.onFailed(TransportException.RequestTimeoutException
                            .build(IpUtil.toAddress(future.getTransport().remoteAddress())));
                } catch (Throwable e) {
                    logger.error("clear timeout response exception", e);
                }
            }
            logger.info("remove timeout request id={} begin={} timeout={}", future.getRequestId(),
                    future.getBeginTime(), timeout);
        }
    }
}
 
Example 4
Source File: PatchworkBiomes.java    From patchwork-api with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void updateFailedBiomes() {
	if (!failedBiomes.isEmpty()) {
		Iterator<Biome> iterator = failedBiomes.iterator();

		while (iterator.hasNext()) {
			Biome biome = iterator.next();
			Biome river = ((RiverSupplier) biome).getRiver();

			if (river == null) {
				continue;
			}

			iterator.remove();

			setRiverIfNotDefault(biome, river);
		}
	}
}
 
Example 5
Source File: ArchiveGalleryProvider.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while (!Thread.currentThread().isInterrupted()) {
    int index;
    InputStream stream;
    synchronized (streams) {
      if (streams.isEmpty()) {
        try {
          streams.wait();
        } catch (InterruptedException e) {
          // Interrupted
          break;
        }
        continue;
      }

      Iterator<Map.Entry<Integer, InputStream>> iterator = streams.entrySet().iterator();
      Map.Entry<Integer, InputStream> entry = iterator.next();
      iterator.remove();
      index = entry.getKey();
      stream = entry.getValue();
      decodingIndex.lazySet(index);
    }

    try {
      Image image = Image.decode(stream, true);
      if (image != null) {
        notifyPageSucceed(index, image);
      } else {
        notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
      }
    } finally {
      decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
    }
  }
}
 
Example 6
Source File: RecentEmojiPageModel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void onCodePointSelected(String emoji) {
  recentlyUsed.remove(emoji);
  recentlyUsed.add(emoji);

  if (recentlyUsed.size() > EMOJI_LRU_SIZE) {
    Iterator<String> iterator = recentlyUsed.iterator();
    iterator.next();
    iterator.remove();
  }

  final LinkedHashSet<String> latestRecentlyUsed = new LinkedHashSet<>(recentlyUsed);
  new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... params) {
      try {
        String serialized = JsonUtils.toJson(latestRecentlyUsed);
        prefs.edit()
             .putString(preferenceName, serialized)
             .apply();
      } catch (IOException e) {
        Log.w(TAG, e);
      }

      return null;
    }
  }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 7
Source File: CacheManager.java    From flower with Apache License 2.0 5 votes vote down vote up
private void clearCache() {
  Iterator<Entry<String, Cache<?>>> it = cacheMap.entrySet().iterator();
  while (it.hasNext()) {
    Entry<String, Cache<?>> cache = it.next();
    if (cache.getValue().isExpired() || cacheExpired(cache.getValue())) {
      it.remove();
    }
  }
}
 
Example 8
Source File: BootstrapLoader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void removeUnwantedJarFiles(List<File> nonLoggingJarFiles, boolean loadOpenAPI) {
    if (loadOpenAPI) {
        return;
    }

    Iterator<File> iterator = nonLoggingJarFiles.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();
        if (file.getName().startsWith("gradle-open-api-")) {
            iterator.remove();
        }
    }
}
 
Example 9
Source File: InMemoryCookieStore.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private <T> void getInternal2(List<HttpCookie> cookies,
                            Map<T, List<HttpCookie>> cookieIndex,
                            Comparable<T> comparator, boolean secureLink)
{
    for (T index : cookieIndex.keySet()) {
        if (comparator.compareTo(index) == 0) {
            List<HttpCookie> indexedCookies = cookieIndex.get(index);
            // check the list of cookies associated with this domain
            if (indexedCookies != null) {
                Iterator<HttpCookie> it = indexedCookies.iterator();
                while (it.hasNext()) {
                    HttpCookie ck = it.next();
                    if (cookieJar.indexOf(ck) != -1) {
                        // the cookie still in main cookie store
                        if (!ck.hasExpired()) {
                            // don't add twice
                            if ((secureLink || !ck.getSecure()) &&
                                    !cookies.contains(ck))
                                cookies.add(ck);
                        } else {
                            it.remove();
                            cookieJar.remove(ck);
                        }
                    } else {
                        // the cookie has beed removed from main store,
                        // so also remove it from domain indexed store
                        it.remove();
                    }
                }
            } // end of indexedCookies != null
        } // end of comparator.compareTo(index) == 0
    } // end of cookieIndex iteration
}
 
Example 10
Source File: V7Producer.java    From coding-snippets with MIT License 5 votes vote down vote up
@Override public void send(Message message) {
 	//处理以前没有发送完留下的对象
 	if( readyForRead.size() > 0){
 		Iterator<Entry<String, List<DefaultBytesMessage>>> it = readyForRead.entrySet().iterator();
 		Entry<String, List<DefaultBytesMessage>> e = null;
 		String key = null;
 		while(it.hasNext()){
 			e = it.next();
 			key =  e.getKey();
 			//能把值更改为true的才获得mapBuffer,并开始写。否则等待下次send
 			if(isReading.get(key).compareAndSet(false, true)){
 				mapBuffer = allMapBuffer.get(key);
 				sendList(e.getValue(), storeOff.get(key));
 				isReading.get(key).set(false);
 				it.remove();
 				storeOff.put(key, 0);
 				
 			}
 		}
 	}
 	/**
 	 * 当存储偏移达到writeThreshold时,写该list. off为下一个要写的数组下标
 	 * 偏移大于writeThreshold时,肯定已经在readyForRead中了。
 	 * 偏移小于于writeThreshold时,不用处理
 	 */
 	if(off == writeThreshold){
 		//能把值更改为true的才获得mapBuffer,并开始写。否则等待下次send
if(isReading.get(queueOrTopic).compareAndSet(false, true)){
	mapBuffer = allMapBuffer.get(queueOrTopic);
	sendList(list , off);
	isReading.get(queueOrTopic).set(false);
	storeOff.put(queueOrTopic, 0);
	
}else{
	//需要清理,但是获得buffer失败,偏移+1,尝试放入readyForRead
	readyForRead.put(queueOrTopic, list);
}
 	}
 }
 
Example 11
Source File: UserManager.java    From openAGV with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  LOG.debug("Sweeping client entries...");
  synchronized (knownClients) {
    Iterator<Map.Entry<ClientID, ClientEntry>> clientIter = knownClients.entrySet().iterator();
    while (clientIter.hasNext()) {
      Map.Entry<ClientID, ClientEntry> curEntry = clientIter.next();
      ClientEntry clientEntry = curEntry.getValue();
      // Only touch the entry if the buffer not currently in use by a
      // client.
      if (!clientEntry.getEventBuffer().hasWaitingClient()) {
        // If the client has been seen since the last run, reset the
        // 'alive' flag.
        if (clientEntry.isAlive()) {
          clientEntry.setAlive(false);
        }
        // If the client hasn't been seen since the last run, remove its
        // ID from the list of known clients - the client has been
        // inactive for long enough.
        else {
          LOG.debug("Removing inactive client entry (client user: {})",
                    clientEntry.getUserName());
          clientIter.remove();
        }
      }
    }
  }
}
 
Example 12
Source File: CubeCapabilityChecker.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private static Set<FunctionDesc> unmatchedAggregations(Collection<FunctionDesc> aggregations, CubeInstance cube) {
    HashSet<FunctionDesc> result = Sets.newHashSet(aggregations);

    CubeDesc cubeDesc = cube.getDescriptor();
    List<FunctionDesc> definedFuncs = cubeDesc.listAllFunctions();

    // check normal aggregations
    result.removeAll(definedFuncs);

    // check dynamic aggregations
    Iterator<FunctionDesc> funcIterator = result.iterator();
    while (funcIterator.hasNext()) {
        FunctionDesc entry = funcIterator.next();
        if (entry instanceof DynamicFunctionDesc) {
            DynamicFunctionDesc dynFunc = (DynamicFunctionDesc) entry;
            // Filter columns cannot be derived
            Collection<TblColRef> definedCols = dynFunc.ifFriendlyForDerivedFilter()
                    ? cubeDesc.listDimensionColumnsIncludingDerived()
                    : cubeDesc.listDimensionColumnsExcludingDerived(true);
            Set<TblColRef> filterCols = Sets.newHashSet(dynFunc.getFilterColumnSet());
            filterCols.removeAll(definedCols);
            if (!filterCols.isEmpty()) {
                continue;
            }

            // All inner funcs should be defined
            Set<FunctionDesc> innerFuncSet = Sets.newHashSet(dynFunc.getRuntimeFuncs());
            innerFuncSet.removeAll(definedFuncs);
            if (!innerFuncSet.isEmpty()) {
                continue;
            }

            funcIterator.remove();
        }
    }
    return result;
}
 
Example 13
Source File: FileAuthorizer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Group deleteGroup(Group group) throws AuthorizationAccessException {
    final AuthorizationsHolder holder = this.authorizationsHolder.get();
    final Tenants tenants = holder.getTenants();
    final Authorizations authorizations = holder.getAuthorizations();

    final List<org.apache.nifi.authorization.file.tenants.generated.Group> groups = tenants.getGroups().getGroup();

    // for each policy iterate over the group reference and remove the group reference if it matches the group being deleted
    for (Policy policy : authorizations.getPolicies().getPolicy()) {
        Iterator<Policy.Group> policyGroupIter = policy.getGroup().iterator();
        while (policyGroupIter.hasNext()) {
            Policy.Group policyGroup = policyGroupIter.next();
            if (policyGroup.getIdentifier().equals(group.getIdentifier())) {
                policyGroupIter.remove();
                break;
            }
        }
    }

    // now remove the actual group from the top-level list of groups
    boolean removedGroup = false;
    Iterator<org.apache.nifi.authorization.file.tenants.generated.Group> iter = groups.iterator();
    while (iter.hasNext()) {
        org.apache.nifi.authorization.file.tenants.generated.Group jaxbGroup = iter.next();
        if (group.getIdentifier().equals(jaxbGroup.getIdentifier())) {
            iter.remove();
            removedGroup = true;
            break;
        }
    }

    if (removedGroup) {
        saveAndRefreshHolder(authorizations, tenants);
        return group;
    } else {
        return null;
    }
}
 
Example 14
Source File: CursorableLinkedList.java    From Penetration_Testing_POC with Apache License 2.0 5 votes vote down vote up
/**
 * Informs all of my registered cursors that they are now
 * invalid.
 */
protected void invalidateCursors() {
    Iterator it = _cursors.iterator();
    while (it.hasNext()) {
        WeakReference ref = (WeakReference) it.next();
        Cursor cursor = (Cursor) ref.get();
        if (cursor != null) {
            // cursor is null if object has been garbage-collected
            cursor.invalidate();
            ref.clear();
        }
        it.remove();
    }
}
 
Example 15
Source File: SqlLogCollector.java    From sofa-acts with Apache License 2.0 5 votes vote down vote up
/**
 * remove duplicated table data
 * 
 * @param virtualTableSet
 */
private static void exculeRepeatTableData(List<VirtualTable> virtualTableSet) {

    if (CollectionUtils.isEmpty(virtualTableSet)) {
        return;
    }

    Iterator<VirtualTable> tableIters = virtualTableSet.iterator();

    List<VirtualTable> originalTableSet = new ArrayList<VirtualTable>();
    originalTableSet.addAll(virtualTableSet);

    int index = 0;
    while (tableIters.hasNext()) {
        VirtualTable virtualTable = tableIters.next();
        index++;
        for (int i = index; i < originalTableSet.size(); i++) {
            if (StringUtils.equalsIgnoreCase(virtualTable.getTableName(),
                originalTableSet.get(i).getTableName())) {
                List<Map<String, Object>> target = virtualTable.getTableData();
                List<Map<String, Object>> other = originalTableSet.get(i).getTableData();

                doExclueRepeatTableData(target, other);

                if (CollectionUtils.isEmpty(target)) {
                    tableIters.remove();
                }
                break;
            }
        }

    }

}
 
Example 16
Source File: ResourcePackInstaller.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
private static void reloadResources() {
    Minecraft mc = Minecraft.getMinecraft();
    GameSettings gameSettings = mc.gameSettings;
    // 因为这时候资源包已经加载了,所以需要重新读取,重新加载
    ResourcePackRepository resourcePackRepository = mc.getResourcePackRepository();
    resourcePackRepository.updateRepositoryEntriesAll();
    List<ResourcePackRepository.Entry> repositoryEntriesAll = resourcePackRepository.getRepositoryEntriesAll();
    List<ResourcePackRepository.Entry> repositoryEntries = Lists.newArrayList();
    Iterator<String> it = gameSettings.resourcePacks.iterator();

    while (it.hasNext()) {
        String packName = it.next();
        for (ResourcePackRepository.Entry entry : repositoryEntriesAll) {
            if (entry.getResourcePackName().equals(packName)) {
                // packFormat 为 3,或者 incompatibleResourcePacks 条目中有的资源包才会加入
                if (entry.getPackFormat() == 3 || gameSettings.incompatibleResourcePacks.contains(entry.getResourcePackName())) {
                    repositoryEntries.add(entry);
                    break;
                }
                // 否则移除
                it.remove();
                logger.warn("移除资源包 {},因为它无法兼容当前版本", entry.getResourcePackName());
            }
        }
    }

    resourcePackRepository.setRepositories(repositoryEntries);
}
 
Example 17
Source File: TemporalRowTimeJoinOperator.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * @return a row time of the oldest unprocessed probe record or Long.MaxValue, if all records
 *         have been processed.
 */
private long emitResultAndCleanUpState(long timerTimestamp) throws Exception {
	List<BaseRow> rightRowsSorted = getRightRowSorted(rightRowtimeComparator);
	long lastUnprocessedTime = Long.MAX_VALUE;

	Iterator<Map.Entry<Long, BaseRow>> leftIterator = leftState.entries().iterator();
	while (leftIterator.hasNext()) {
		Map.Entry<Long, BaseRow> entry = leftIterator.next();
		BaseRow leftRow = entry.getValue();
		long leftTime = getLeftTime(leftRow);

		if (leftTime <= timerTimestamp) {
			Optional<BaseRow> rightRow = latestRightRowToJoin(rightRowsSorted, leftTime);
			if (rightRow.isPresent()) {
				if (joinCondition.apply(leftRow, rightRow.get())) {
					outRow.replace(leftRow, rightRow.get());
					collector.collect(outRow);
				}
			}
			leftIterator.remove();
		} else {
			lastUnprocessedTime = Math.min(lastUnprocessedTime, leftTime);
		}
	}

	cleanupState(timerTimestamp, rightRowsSorted);
	return lastUnprocessedTime;
}
 
Example 18
Source File: Spans.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Sort the spans in ascending order by their
 * start position. After the spans are sorted
 * collapse any spans that intersect into a
 * single span. The result is a sorted,
 * non-overlapping list of spans.
 */
private void sortAndCollapse() {

    Collections.sort(mSpans);
    mAddsSinceSort = 0;

    Iterator iter = mSpans.iterator();

    /* Have 'span' start at the first span in
     * the collection. The collection may be empty
     * so we're careful.
     */
    Span span = null;
    if (iter.hasNext()) {
        span = (Span) iter.next();
    }

    /* Loop over the spans collapsing those that intersect
     * into a single span.
     */
    while (iter.hasNext()) {

        Span nextSpan = (Span) iter.next();

        /* The spans are in ascending start position
         * order and so the next span's starting point
         * is either in the span we are trying to grow
         * or it is beyond the first span and thus the
         * two spans do not intersect.
         *
         * span:    <----------<
         * nextSpan:        <------         (intersects)
         * nextSpan:                <------ (doesn't intersect)
         *
         * If the spans intersect then we'll remove
         * nextSpan from the list. If nextSpan's
         * ending was beyond the first's then
         * we extend the first.
         *
         * span:    <----------<
         * nextSpan:   <-----<              (don't change span)
         * nextSpan:        <-----------<   (grow span)
         */

        if (span.subsume(nextSpan)) {
            iter.remove();

        /* The next span did not intersect the current
         * span and so it can not be collapsed. Instead
         * it becomes the start of the next set of spans
         * to be collapsed.
         */
        } else {
            span = nextSpan;
        }
    }
}
 
Example 19
Source File: ActivityUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 结束全部 Activity 除忽略的 Activity 外
 * @param clazzs Class(Activity)[]
 * @return {@link ActivityUtils}
 */
public ActivityUtils finishAllActivityToIgnore(final Class<?>... clazzs) {
    if (clazzs != null && clazzs.length != 0) {
        synchronized (mActivityStacks) {
            // 保存新的堆栈, 防止出现同步问题
            Stack<Activity> stack = new Stack<>();
            stack.addAll(mActivityStacks);
            // 清空全部, 便于后续操作处理
            mActivityStacks.clear();
            // 判断是否销毁
            boolean isRemove;
            // 进行遍历移除
            Iterator<Activity> iterator = stack.iterator();
            while (iterator.hasNext()) {
                Activity activity = iterator.next();
                // 判断是否想要关闭的 Activity
                if (activity != null) {
                    // 默认需要销毁
                    isRemove = true;
                    // 循环判断
                    for (int i = 0, len = clazzs.length; i < len; i++) {
                        // 判断是否相同
                        if (activity.getClass() == clazzs[i]) {
                            isRemove = false;
                            break;
                        }
                    }
                    // 判断是否销毁
                    if (isRemove) {
                        // 如果 Activity 没有 finish 则进行 finish
                        if (!activity.isFinishing()) {
                            activity.finish();
                        }
                        // 删除对应的 Item
                        iterator.remove();
                    }
                } else {
                    // 删除对应的 Item
                    iterator.remove();
                }
            }
            // 把不符合条件的保存回去
            mActivityStacks.addAll(stack);
            // 移除数据, 并且清空内存
            stack.clear();
            stack = null;
        }
    }
    return this;
}
 
Example 20
Source File: HunterPlugin.java    From plugins with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Iterates over all the traps that were placed by the local player and
 * checks if the trap is still there. If the trap is gone, it removes
 * the trap from the local players trap collection.
 */
@Subscribe
private void onGameTick(GameTick event)
{
	// Check if all traps are still there, and remove the ones that are not.
	Iterator<Map.Entry<WorldPoint, HunterTrap>> it = traps.entrySet().iterator();
	Tile[][][] tiles = client.getScene().getTiles();

	Instant expire = Instant.now().minus(HunterTrap.TRAP_TIME.multipliedBy(2));

	while (it.hasNext())
	{
		Map.Entry<WorldPoint, HunterTrap> entry = it.next();
		HunterTrap trap = entry.getValue();
		WorldPoint world = entry.getKey();
		LocalPoint local = LocalPoint.fromWorld(client, world);

		// Not within the client's viewport
		if (local == null)
		{
			// Cull very old traps
			if (trap.getPlacedOn().isBefore(expire))
			{
				log.debug("Trap removed from personal trap collection due to timeout, {} left", traps.size());
				it.remove();
				continue;
			}
			continue;
		}

		Tile tile = tiles[world.getPlane()][local.getSceneX()][local.getSceneY()];
		GameObject[] objects = tile.getGameObjects();

		boolean containsBoulder = false;
		boolean containsAnything = false;
		boolean containsYoungTree = false;
		for (GameObject object : objects)
		{
			if (object != null)
			{
				containsAnything = true;
				if (object.getId() == ObjectID.BOULDER_19215 || object.getId() == ObjectID.LARGE_BOULDER)
				{
					containsBoulder = true;
					break;
				}

				// Check for young trees (used while catching salamanders) in the tile.
				// Otherwise, hunter timers will never disappear after a trap is dismantled
				if (object.getId() == ObjectID.YOUNG_TREE_8732 || object.getId() == ObjectID.YOUNG_TREE_8990 ||
					object.getId() == ObjectID.YOUNG_TREE_9000 || object.getId() == ObjectID.YOUNG_TREE_9341)
				{
					containsYoungTree = true;
				}
			}
		}

		if (!containsAnything || containsYoungTree)
		{
			it.remove();
			log.debug("Trap removed from personal trap collection, {} left", traps.size());
		}
		else if (containsBoulder) // For traps like deadfalls. This is different because when the trap is gone, there is still a GameObject (boulder)
		{
			it.remove();
			log.debug("Special trap removed from personal trap collection, {} left", traps.size());

			// Case we have notifications enabled and the action was not manual, throw notification
			if (config.maniacalMonkeyNotify() && trap.getObjectId() == ObjectID.MONKEY_TRAP &&
				!trap.getState().equals(HunterTrap.State.FULL) && !trap.getState().equals(HunterTrap.State.OPEN))
			{
				notifier.notify("The monkey escaped.");
			}
		}
	}

	lastTickLocalPlayerLocation = client.getLocalPlayer().getWorldLocation();
}