Java Code Examples for java.util.SortedSet#size()

The following examples show how to use java.util.SortedSet#size() . 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: PrimePowers_DefaultImpl.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check relationship between set of divisors and powermap.
 * Hypothesis confirmed from 0..203846.
 * 
 * @param args ignored
 */
public static void main(String[] args) {
	ConfigUtil.initProject();
	for (int n=0; n<1000; n++) {
		BigInteger bigN = BigInteger.valueOf(n);
		SortedSet<BigInteger> divisors = Divisors.getDivisors(bigN);
		int numberOfDivisors = divisors.size();
		PrimePowers primePowers = PrimePowers_DefaultImpl.valueOf(bigN);
		MpiPowerMap powerMap = MpiPowerMap.create(primePowers);
		int powerMapSize = powerMap.size();
		LOG.info("n=" + n + " has " + numberOfDivisors + " divisors, and power map has " + powerMapSize + " entries");
		int correctedPowerMapSize = n>0 ? powerMapSize + primePowers.getDim() + 1 : 0;
		LOG.info("correctedPowerMapSize = " + correctedPowerMapSize);
		// the power map is missing the unit entries (only one prime) and the empty entry!
		if (numberOfDivisors!=correctedPowerMapSize) {
			LOG.info("n = " + n);
			LOG.info("divisors = " + divisors);
			LOG.info("powerMap = " + powerMap);
			throw new IllegalStateException("my hypothesis is wrong for n=" + n);
		}
	}
}
 
Example 2
Source File: SingleModuleProperties.java    From netbeans with Apache License 2.0 6 votes vote down vote up
String[] getAllTokens() {
    if (allTokens == null) {
        try {
            SortedSet<String> provTokens = new TreeSet<String>();
            provTokens.addAll(Arrays.asList(IDE_TOKENS));
            for (ModuleEntry me : getModuleList().getAllEntries()) {
                provTokens.addAll(Arrays.asList(me.getProvidedTokens()));
            }
            String[] result = new String[provTokens.size()];
            return provTokens.toArray(result);
        } catch (IOException e) {
            allTokens = new String[0];
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
        }
    }
    return allTokens;
}
 
Example 3
Source File: RangeUtil.java    From kylin with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Range<Integer>> buildRanges(SortedSet<Integer> values) {
    ArrayList<Range<Integer>> ranges = Lists.newArrayList();

    if (values == null || values.isEmpty())
        return ranges;

    Iterator<Integer> iter = values.iterator();
    int lastBegin = iter.next();
    int lastEnd = lastBegin;
    int temp = 0;
    for (int index = 1; index < values.size(); index++) {
        temp = iter.next();
        if (temp - lastEnd != 1) {
            ranges.add(Range.closed(lastBegin, lastEnd));
            lastBegin = temp;
        }
        lastEnd = temp;
    }
    ranges.add(Range.closed(lastBegin, lastEnd));
    return ranges;
}
 
Example 4
Source File: LongMap.java    From netbeans with Apache License 2.0 6 votes vote down vote up
long[] getBiggestObjectsByRetainedSize(int number) {
    SortedSet bigObjects = new TreeSet();
    long[] bigIds = new long[number];
    long min = 0;
    for (long index=0;index<fileSize;index+=ENTRY_SIZE) {
        long id = getID(index);
        if (id != 0) {
            long retainedSize = createEntry(index).getRetainedSize();
            if (bigObjects.size()<number) {
                bigObjects.add(new RetainedSizeEntry(id,retainedSize));
                min = ((RetainedSizeEntry)bigObjects.last()).retainedSize;
            } else if (retainedSize>min) {
                bigObjects.remove(bigObjects.last());
                bigObjects.add(new RetainedSizeEntry(id,retainedSize));
                min = ((RetainedSizeEntry)bigObjects.last()).retainedSize;
            }
        }
    }
    int i = 0;
    Iterator it = bigObjects.iterator();
    while(it.hasNext()) {
        bigIds[i++]=((RetainedSizeEntry)it.next()).instanceId;
    }
    return bigIds;
}
 
Example 5
Source File: QueryMetricsResponseSerializer.java    From heroic with Apache License 2.0 6 votes vote down vote up
void writeTags(
    JsonGenerator g, final Map<String, SortedSet<String>> tags
) throws IOException {
    g.writeFieldName("tags");

    g.writeStartObject();

    for (final Map.Entry<String, SortedSet<String>> pair : tags.entrySet()) {
        final SortedSet<String> values = pair.getValue();

        if (values.size() != 1) {
            continue;
        }

        g.writeStringField(pair.getKey(), values.iterator().next());
    }

    g.writeEndObject();
}
 
Example 6
Source File: TaskReportRenderer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void writeTask(TaskDetails task, String prefix) {
    getTextOutput().text(prefix);
    getTextOutput().withStyle(Identifier).text(task.getPath());
    if (GUtil.isTrue(task.getDescription())) {
        getTextOutput().withStyle(Description).format(" - %s", task.getDescription());
    }
    if (detail) {
        SortedSet<Path> sortedDependencies = new TreeSet<Path>();
        for (TaskDetails dependency : task.getDependencies()) {
            sortedDependencies.add(dependency.getPath());
        }
        if (sortedDependencies.size() > 0) {
            getTextOutput().withStyle(Info).format(" [%s]", CollectionUtils.join(", ", sortedDependencies));
        }
    }
    getTextOutput().println();
}
 
Example 7
Source File: ColocUtilTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetColocOutPhases() throws Exception {
    PhaseManagerImpl phaseMgr = new PhaseManagerImpl();

    SortedSet<Phase> list = phaseMgr.getOutPhases();
    int size1 = list.size();
    ColocUtil.setPhases(list, Phase.SETUP, Phase.POST_LOGICAL);

    assertNotSame("The list size should not be same",
                  size1, list.size());
    assertEquals("Expecting Phase.SETUP",
                 list.first().getName(),
                 Phase.SETUP);
    assertEquals("Expecting Phase.POST_LOGICAL",
                 list.last().getName(),
                 Phase.POST_LOGICAL);

}
 
Example 8
Source File: SocketUtils.java    From chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Find the requested number of available ports for this {@code SocketType},
 * each randomly selected from the range [{@code minPort}, {@code maxPort}].
 *
 * @param numRequested
 *                 the number of available ports to find
 * @param minPort
 *                 the minimum port number
 * @param maxPort
 *                 the maximum port number
 *
 * @return a sorted set of available port numbers for this socket type
 *
 * @throws IllegalStateException
 *                 if the requested number of available ports could not be found
 */
SortedSet<Integer> findAvailablePorts(int numRequested, int minPort, int maxPort) {
        Assert.assertTrue("'minPort' must be greater than 0", minPort > 0);
        Assert.assertTrue("'maxPort' must be greater than 'minPort'", maxPort > minPort);
        Assert.assertTrue("'maxPort' must be less than or equal to " + PORT_RANGE_MAX, maxPort <= PORT_RANGE_MAX);
        Assert.assertTrue("'numRequested' must be greater than 0", numRequested > 0);
        Assert.assertTrue("'numRequested' must not be greater than 'maxPort' - 'minPort'", (maxPort - minPort) >= numRequested);

        final SortedSet<Integer> availablePorts = new TreeSet<Integer>();
        int attemptCount = 0;
        while((++attemptCount <= numRequested + 100) && (availablePorts.size() < numRequested)) {
                availablePorts.add(findAvailablePort(minPort, maxPort));
        }

        if(availablePorts.size() != numRequested) {
                throw new IllegalStateException(String.format(
                                "Could not find %d available %s ports in the range [%d, %d]", numRequested, name(), minPort,
                                maxPort));
        }

        return availablePorts;
}
 
Example 9
Source File: TranslitUtil.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
public TranslitUtil(InputStream is) {
    SortedSet<SymbolReplacement> symbolReplacements = loadReplacements(is);

    if (symbolReplacements.size() == 0) {
        Log.i(TAG, "No transliteration replacements loaded");
        symbols = null;
        replacements = null;
    } else {
        Log.i(TAG, "Loaded " + symbolReplacements.size() + " transliteration replacements");
        symbols = new int[symbolReplacements.size()];
        replacements = new String[symbolReplacements.size()];

        int pos = 0;
        for (SymbolReplacement sr : symbolReplacements) {
            symbols[pos] = sr.symbol;
            replacements[pos] = sr.replacement;
            pos++;
        }
    }
}
 
Example 10
Source File: DefaultTaskExecutionService.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private Set<TaskExecution> getTaskExecutions(Set<Long> ids) {
	Set<TaskExecution> taskExecutions = new HashSet<>();
	final SortedSet<Long> nonExistingTaskExecutions = new TreeSet<>();
	for (Long id : ids) {
		final TaskExecution taskExecution = this.taskExplorer.getTaskExecution(id);
		if (taskExecution == null) {
			nonExistingTaskExecutions.add(id);
		}
		else {
			taskExecutions.add(taskExecution);
		}
	}
	if (!nonExistingTaskExecutions.isEmpty()) {
		if (nonExistingTaskExecutions.size() == 1) {
			throw new NoSuchTaskExecutionException(nonExistingTaskExecutions.first());
		}
		else {
			throw new NoSuchTaskExecutionException(nonExistingTaskExecutions);
		}
	}
	return taskExecutions;
}
 
Example 11
Source File: JdbcDatabaseMetadata.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public ResultSet getIndexInfo(String catalog, String schema, String tbl, boolean unique,
    boolean approximate) throws SQLException {
    conn.ensureNotClosed();

    List<List<?>> rows = Collections.emptyList();

    if (isValidCatalog(catalog)) {
        // Currently we are treating schema and tbl as sql patterns.
        SortedSet<JdbcIndexMeta> idxMetas = meta.getIndexesMeta(schema, tbl);

        rows = new ArrayList<>(idxMetas.size());

        for (JdbcIndexMeta idxMeta : idxMetas)
            rows.addAll(indexRows(idxMeta));
    }

    return new JdbcResultSet(true, null,
        conn.createStatement0(),
        Collections.<String>emptyList(),
        asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "NON_UNIQUE", "INDEX_QUALIFIER",
            "INDEX_NAME", "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", "ASC_OR_DESC", "CARDINALITY",
            "PAGES", "FILTER_CONDITION"),
        asList(String.class.getName(), String.class.getName(), String.class.getName(),
            Boolean.class.getName(), String.class.getName(), String.class.getName(), Short.class.getName(),
            Short.class.getName(), String.class.getName(), String.class.getName(), Integer.class.getName(),
            Integer.class.getName(), String.class.getName()),
        rows, true
    );
}
 
Example 12
Source File: DecisionProcedureAlgorithms.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
protected Outcome decide_IFX_Nonconcrete(Primitive condition, SortedSet<DecisionAlternative_IFX> result) 
throws DecisionException {	
    final boolean shouldRefine;
    final DecisionAlternative_IFX T = DecisionAlternative_IFX.toNonconcrete(true);
    final DecisionAlternative_IFX F = DecisionAlternative_IFX.toNonconcrete(false);

    //TODO what if condition is neither Simplex, nor Any, nor Expression (i.e., FunctionApplication, Widening/NarrowingConversion, PrimitiveSymbolic, Term)?
    try {
        final Expression exp = (Expression) condition; 
        //this implementation saves one sat check in 50% cases
        //(it exploits the fact that if exp is unsat 
        //exp.not() is valid)
        if (isAny(exp.getFirstOperand()) || isAny(exp.getSecondOperand())) {
            result.add(T);
            result.add(F);
            shouldRefine = false; //"don't care" does not require refinement
        } else if (isSat(exp)) {
            result.add(T);
            final Expression expNot = (Expression) this.calc.push(condition).not().pop(); 
            if (isSat(expNot)) {
                result.add(F);
            }
            shouldRefine = (result.size() > 1);
        } else {
            //exp is unsat, thus its negation is valid
            result.add(F);
            shouldRefine = false;
        }
    } catch (InvalidOperandException | InvalidTypeException | InvalidInputException e) {
        //this should never happen as arguments have been checked by the caller
        throw new UnexpectedInternalException(e);
    }
    return Outcome.val(shouldRefine, true);
}
 
Example 13
Source File: ResourceBundleGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static String toLocaleList(SortedSet<String> set) {
    StringBuilder sb = new StringBuilder(set.size() * 6);
    for (String id : set) {
        if (!"root".equals(id)) {
            if (sb.length() > 0) {
                sb.append(' ');
            }
            sb.append(id);
        }
    }
    return sb.toString();
}
 
Example 14
Source File: MagicCombatCreature.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
void setAttacker(final MagicGame game,final Set<MagicCombatCreature> blockers) {
    final SortedSet<MagicCombatCreature> candidateBlockersSet =
            new TreeSet<>(new BlockerComparator(this));
    for (final MagicCombatCreature blocker : blockers) {
        if (blocker.permanent.canBlock(permanent)) {
            candidateBlockersSet.add(blocker);
        }
    }
    candidateBlockers=new MagicCombatCreature[candidateBlockersSet.size()];
    candidateBlockersSet.toArray(candidateBlockers);

    attackerScore=ArtificialScoringSystem.getAttackerScore(this);
}
 
Example 15
Source File: AuthoringConditionController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Extract form content to QaCondition.
    *
    * @param request
    * @param form
    * @throws QaException
    */
   private void extractFormToQaCondition(HttpServletRequest request, QaConditionForm form) throws Exception {

SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(form.getSessionMapID());
// check whether it is "edit(old item)" or "add(new item)"
SortedSet<QaCondition> conditionSet = getQaConditionSet(sessionMap);
int orderId = form.getOrderId();
QaCondition condition = null;

if (orderId == -1) { // add
    String properConditionName = qaService.createConditionName(conditionSet);
    condition = form.extractCondition();
    condition.setName(properConditionName);
    int maxOrderId = 1;
    if (conditionSet != null && conditionSet.size() > 0) {
	QaCondition last = conditionSet.last();
	maxOrderId = last.getOrderId() + 1;
    }
    condition.setOrderId(maxOrderId);
    conditionSet.add(condition);
} else { // edit
    List<QaCondition> conditionList = new ArrayList<>(conditionSet);
    condition = conditionList.get(orderId - 1);
    form.extractCondition(condition);
}

Integer[] selectedItems = form.getSelectedItems();
List<QaQuestionDTO> questions = getQuestionList(sessionMap);

condition.temporaryQuestionDTOSet.clear();
for (Integer selectedItem : selectedItems) {
    for (QaQuestionDTO question : questions) {
	if (selectedItem.equals(new Integer(question.getDisplayOrder()))) {
	    condition.temporaryQuestionDTOSet.add(question);
	}
    }
}

   }
 
Example 16
Source File: AuthoringChatConditionController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Extract form content to taskListContent.
    */
   private void extractFormToChatCondition(HttpServletRequest request, ChatConditionForm chatConditionForm)
    throws Exception {

SessionMap sessionMap = (SessionMap) request.getSession().getAttribute(chatConditionForm.getSessionMapID());
// check whether it is "edit(old item)" or "add(new item)"
SortedSet<ChatCondition> conditionSet = getChatConditionSet(sessionMap);
int orderId = chatConditionForm.getOrderId();
ChatCondition condition = null;

if (orderId == -1) { // add
    String properConditionName = chatService.createConditionName(conditionSet);
    condition = chatConditionForm.extractCondition();
    condition.setName(properConditionName);
    int maxSeq = 1;
    if (conditionSet != null && conditionSet.size() > 0) {
	ChatCondition last = conditionSet.last();
	maxSeq = last.getOrderId() + 1;
    }
    condition.setOrderId(maxSeq);
    conditionSet.add(condition);
} else { // edit
    List<ChatCondition> conditionList = new ArrayList<>(conditionSet);
    condition = conditionList.get(orderId - 1);
    chatConditionForm.extractCondition(condition);
}
   }
 
Example 17
Source File: AppListBuilder.java    From swift-k with Apache License 2.0 4 votes vote down vote up
public void getData(JSONEncoder e) throws IOException {
    SortedSet<ApplicationItem> sorted = getInstances(name, stateFilter, hostFilter);
    
    if (pageSize == -1) {
        pageSize = sorted.size();
    }
    int start = (page - 1) * pageSize;
    int index = 0;
    e.beginMap();
    
    String title;
    if (stateFilter == -1) {
        if (name.isEmpty()) {
            title =  "All application invocations";
        }
        else {
            title = "Invocations of application \"" + name + "\"";
        }
    }
    else {
        if (name.isEmpty()) {
            title = ApplicationState.values()[stateFilter] + " application invocations";
        }
        else {
            title = ApplicationState.values()[stateFilter] + " invocations of application \"" + name + "\"";
        }
    }
    if (hostFilter != null) {
        title = title + " on site \"" + hostFilter + "\"";
    }
    e.writeMapItem("title", title);
    db.writePagingData(e, sorted.size(), page, pageSize);
    e.writeMapItem("name", name);
    e.writeMapItem("state", stateFilter);
    e.writeMapItem("host", hostFilter);
    for (ApplicationItem item : sorted) {
        if (index == start) {
            e.writeMapKey("data");
            e.beginArray();
        }
        if (index >= start) {
            ApplicationState state = item.getState();
            e.beginArrayItem();
            e.beginMap();
            e.writeMapItem("id", item.getID());
            e.writeMapItem("state", state.ordinal());
            e.writeMapItem("startTime", item.getStartTime());
            e.writeMapItem("host", item.getHost());
            if (item.getWorkerId() != null) {
                e.writeMapItem("worker", item.getWorkerId());
            }
            e.writeMapItem("args", item.getArguments());
            if (state.isTerminal()) {
                e.writeMapItem("runTime", item.getCurrentStateTime() - item.getStartTime());
            }
            else {
                e.writeMapItem("runTime", 0L);
            }
            e.endMap();
            e.endArrayItem();
        }
        if (index > start + pageSize) {
            e.endArray();
            e.endMap();
            return;
        }
        index++;
    }
    if (sorted.size() > 0) {
        e.endArray();
    }
    e.endMap();
}
 
Example 18
Source File: BasicImageContext.java    From pumpernickel with MIT License 4 votes vote down vote up
VariableWidthFunction(int minX, int maxX, Point2D topLeft,
		Point2D topRight, Point2D bottomRight, Point2D bottomLeft)
		throws LineSegmentIntersectionException {
	this.minX = minX;
	this.maxX = maxX;

	if (intersect(topLeft, bottomLeft, topRight, bottomRight))
		throw new LineSegmentIntersectionException();
	if (intersect(topLeft, topRight, bottomLeft, bottomRight))
		throw new LineSegmentIntersectionException();

	SortedSet<Point2D> horizontalList = new TreeSet<Point2D>(
			xComparator);
	horizontalList.add(topLeft);
	horizontalList.add(topRight);
	horizontalList.add(bottomLeft);
	horizontalList.add(bottomRight);
	double leftX = horizontalList.first().getX();
	double rightX = horizontalList.last().getX();

	SortedSet<Point> left = new TreeSet<Point>(yComparator);
	SortedSet<Point> right = new TreeSet<Point>(yComparator);

	Point2D[] path = new Point2D[] { topLeft, topRight, bottomRight,
			bottomLeft };
	for (int a = 0; a < path.length; a++) {
		int prev = (a - 1 + path.length) % path.length;
		int next = (a + 1 + path.length) % path.length;

		boolean bottomMostVertex = path[prev].getY() <= path[a].getY()
				&& path[next].getY() <= path[a].getY();
		boolean topMostVertex = path[prev].getY() >= path[a].getY()
				&& path[next].getY() >= path[a].getY();

		if (path[a].getX() == leftX) {
			addPoint2D(left, path[a], false);

			if (bottomMostVertex || topMostVertex) {
				if (path[prev].getX() <= path[a].getX()) {
					addPoint2D(left, path[prev], false);
				} else if (path[next].getX() <= path[a].getX()) {
					addPoint2D(left, path[next], false);
				}
			} else {
				addPoint2D(left, path[prev], false);
				addPoint2D(left, path[next], false);
			}
		}

		if (path[a].getX() == rightX) {
			addPoint2D(right, path[a], true);

			if (bottomMostVertex || topMostVertex) {
				if (path[prev].getX() >= path[a].getX()) {
					addPoint2D(right, path[prev], true);
				} else if (path[next].getX() >= path[a].getX()) {
					addPoint2D(right, path[next], true);
				}
			} else {
				addPoint2D(right, path[prev], true);
				addPoint2D(right, path[next], true);
			}
		}
	}

	left = removeRedundantYs(left, false);
	right = removeRedundantYs(right, true);

	this.leftX = new int[left.size()];
	this.leftY = new int[left.size()];
	store(left, this.leftX, this.leftY);

	this.rightX = new int[right.size()];
	this.rightY = new int[right.size()];
	store(right, this.rightX, this.rightY);
}
 
Example 19
Source File: SortedRanges.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
/**
 * Add the range indices. It is ensured that the added range 
 * doesn't overlap the existing ranges. If it overlaps, the 
 * existing overlapping ranges are removed and a single range 
 * having the superset of all the removed ranges and this range 
 * is added. 
 * If the range is of 0 length, doesn't do anything.
 * @param range Range to be added.
 */
synchronized void add(Range range){
  if(range.isEmpty()) {
    return;
  }
  
  long startIndex = range.getStartIndex();
  long endIndex = range.getEndIndex();
  //make sure that there are no overlapping ranges
  SortedSet<Range> headSet = ranges.headSet(range);
  if(headSet.size()>0) {
    Range previousRange = headSet.last();
    LOG.debug("previousRange "+previousRange);
    if(startIndex<previousRange.getEndIndex()) {
      //previousRange overlaps this range
      //remove the previousRange
      if(ranges.remove(previousRange)) {
        indicesCount-=previousRange.getLength();
      }
      //expand this range
      startIndex = previousRange.getStartIndex();
      endIndex = endIndex>=previousRange.getEndIndex() ?
                        endIndex : previousRange.getEndIndex();
    }
  }
  
  Iterator<Range> tailSetIt = ranges.tailSet(range).iterator();
  while(tailSetIt.hasNext()) {
    Range nextRange = tailSetIt.next();
    LOG.debug("nextRange "+nextRange +"   startIndex:"+startIndex+
        "  endIndex:"+endIndex);
    if(endIndex>=nextRange.getStartIndex()) {
      //nextRange overlaps this range
      //remove the nextRange
      tailSetIt.remove();
      indicesCount-=nextRange.getLength();
      if(endIndex<nextRange.getEndIndex()) {
        //expand this range
        endIndex = nextRange.getEndIndex();
        break;
      }
    } else {
      break;
    }
  }
  add(startIndex,endIndex);
}
 
Example 20
Source File: SplitFetcherTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Test
public void testWakeup() throws InterruptedException {
	BlockingQueue<RecordsWithSplitIds<int[]>> elementQueue = new ArrayBlockingQueue<>(1);
	SplitFetcher<int[], MockSourceSplit> fetcher =
			new SplitFetcher<>(
					0,
					elementQueue,
					new MockSplitReader(2, true, true),
					() -> {});

	// Prepare the splits.
	List<MockSourceSplit> splits = new ArrayList<>();
	for (int i = 0; i < NUM_SPLITS; i++) {
		splits.add(new MockSourceSplit(i, 0, NUM_RECORDS_PER_SPLIT));
		int base = i * NUM_RECORDS_PER_SPLIT;
		for (int j = base; j < base + NUM_RECORDS_PER_SPLIT; j++) {
			splits.get(splits.size() - 1).addRecord(j);
		}
	}
	// Add splits to the fetcher.
	fetcher.addSplits(splits);

	// A thread drives the fetcher.
	Thread fetcherThread = new Thread(fetcher, "FetcherThread");

	SortedSet<Integer> recordsRead = Collections.synchronizedSortedSet(new TreeSet<>());

	// A thread waking up the split fetcher frequently.
	AtomicInteger wakeupTimes = new AtomicInteger(0);
	AtomicBoolean stop = new AtomicBoolean(false);
	Thread interrupter = new Thread("Interrupter") {
		@Override
		public void run() {
			int lastInterrupt = 0;
			while (recordsRead.size() < NUM_TOTAL_RECORDS && !stop.get()) {
				int numRecordsRead = recordsRead.size();
				if (numRecordsRead >= lastInterrupt + INTERRUPT_RECORDS_INTERVAL) {
					fetcher.wakeUp(false);
					wakeupTimes.incrementAndGet();
					lastInterrupt = numRecordsRead;
				}
			}
		}
	};

	try {
		fetcherThread.start();
		interrupter.start();

		while (recordsRead.size() < NUM_SPLITS * NUM_RECORDS_PER_SPLIT) {
			elementQueue.take().recordsBySplits().values().forEach(records ->
					// Ensure there is no duplicate records.
					records.forEach(arr -> assertTrue(recordsRead.add(arr[0]))));
		}

		assertEquals(NUM_TOTAL_RECORDS, recordsRead.size());
		assertEquals(0, (int) recordsRead.first());
		assertEquals(NUM_TOTAL_RECORDS - 1, (int) recordsRead.last());
		assertTrue(wakeupTimes.get() > 0);
	} finally {
		stop.set(true);
		fetcher.shutdown();
		fetcherThread.join();
		interrupter.join();
	}
}