Created
June 21, 2014 07:46
-
-
Save machielg/44697c2539b8b9f6a822 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Spliterator; | |
import java.util.function.Consumer; | |
import com.datastax.driver.core.ResultSet; | |
import com.datastax.driver.core.Row; | |
public class ResultSetSpliterator implements Spliterator<Row> { | |
private final ResultSet rs; | |
private final Iterator<Row> iterator; | |
private long estimate = Long.MAX_VALUE; | |
public ResultSetSpliterator(ResultSet rs) { | |
this.rs = rs; | |
this.iterator = rs.iterator(); | |
} | |
@Override | |
public boolean tryAdvance(Consumer<? super Row> action) { | |
if (!iterator.hasNext()) { | |
action.accept(iterator.next()); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
@Override | |
public Spliterator<Row> trySplit() { | |
int availableWithoutFetching = rs.getAvailableWithoutFetching(); | |
if (availableWithoutFetching == 0) { | |
if (rs.isFullyFetched()) { | |
//done | |
return null; | |
} else { | |
//block for more | |
iterator.hasNext(); | |
availableWithoutFetching = rs.getAvailableWithoutFetching(); | |
} | |
} else { | |
System.out.println("CACHE HIT"); | |
} | |
rs.fetchMoreResults(); | |
estimate -= availableWithoutFetching; | |
System.out.println(String.format("Splitting off %d rows", availableWithoutFetching)); | |
List<Row> cached = new ArrayList<>(availableWithoutFetching); | |
for (int i = 0; i < availableWithoutFetching; i++) { | |
cached.add(iterator.next()); | |
} | |
return cached.spliterator(); | |
} | |
@Override | |
public long estimateSize() { | |
return estimate; | |
} | |
public void forEachRemaining(Consumer<? super Row> action) { | |
this.iterator.forEachRemaining(action); | |
} | |
@Override | |
public int characteristics() { | |
return Spliterator.IMMUTABLE | Spliterator.NONNULL; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment