PrefetchIterator implements Iterator<K> { public long size() { if (size != -1) { return size; } if (!fastSize) { if (prefetchDone || position > maxPrefetch) { return -1; } } prefetchDone = true; ArrayList<K> list = new ArrayList<K>(); long end; if (timeout <= 0) { end = 0; } else { long nanos = System.nanoTime(); end = nanos + timeout * 1000 * 1000; } while (true) { if (!it.hasNext()) { size = position; break; } if (position > maxPrefetch) { break; } if (position > minPrefetch) { if (end == 0 || System.nanoTime() > end) { break; } } position++; list.add(it.next()); } if (list.size() > 0) { prefetchIterator = list.iterator(); position -= list.size(); } if (size == -1 && fastSize) { if (fastSizeCallback != null) { size = fastSizeCallback.getSize(SizePrecision.EXACT, Long.MAX_VALUE); } } return size; } PrefetchIterator(Iterator<K> it, PrefetchOptions options); @Override boolean hasNext(); @Override K next(); @Override void remove(); long size();  }
@Test public void testFastSize() { Iterable<Integer> s; PrefetchIterator<Integer> it; s = seq(0, 21); it = new PrefetchIterator<Integer>(s.iterator(), new PrefetchOptions() { { size = -1; fastSize = true; fastSizeCallback = new Result() { @Override public String[] getColumnNames() { return null; } @Override public String[] getColumnSelectorNames() { return null; } @Override public Iterable<? extends ResultRow> getRows() { return null; } @Override public String[] getSelectorNames() { return null; } @Override public long getSize() { return 100; } @Override public long getSize(SizePrecision precision, long max) { return 100; } }; } }); assertEquals(21, it.size()); }
@Test public void testKnownSize() { Iterable<Integer> s; PrefetchIterator<Integer> it; s = seq(0, 100); it = new PrefetchIterator<Integer>(s.iterator(), new PrefetchOptions() { { min = 5; timeout = 0; max = 10; size = 200; } }); assertEquals(200, it.size()); }
@Test public void testTimeout() { Iterable<Integer> s; PrefetchIterator<Integer> it; final long testTimeout = 10; s = seq(0, 100, 10); it = new PrefetchIterator<Integer>(s.iterator(), new PrefetchOptions() { { min = 5; timeout = testTimeout; max = 10; size = -1; } }); assertEquals(-1, it.size()); s = seq(0, 100); it = new PrefetchIterator<Integer>(s.iterator(), new PrefetchOptions() { { min = 5; timeout = testTimeout; max = 1000; size = -1; } }); assertEquals(100, it.size()); }