use of com.oath.cyclops.react.async.subscription.Subscription in project cyclops by aol.
the class LazyReact method iterate.
/**
* Iterate infinitely using the supplied seed and function
* Iteration is synchronized to support multiple threads using the same iterator.
*
* <pre>
* {@code
* new LazyReact().objectPoolingOn()
* .iterate(1,i->i+1)
* .limit(1_000_000)
* .map(this::process)
* .forEach(this::save);
*
* }
* </pre>
*
* @see FutureStream#iterate for an alternative which does not synchronize iteration
* @param seed Initial value
* @param f Function that performs the iteration
* @return FutureStream
*/
public <U> FutureStream<U> iterate(final U seed, final UnaryOperator<U> f) {
final Subscription sub = new Subscription();
final Supplier<U> supplier = new Supplier<U>() {
@SuppressWarnings("unchecked")
U t = (U) NONE;
@Override
public U get() {
return t = t == NONE ? seed : f.apply(t);
}
};
return construct(StreamSupport.<U>stream(new InfiniteClosingSpliteratorFromSupplier<U>(Long.MAX_VALUE, supplier, sub), false));
}
use of com.oath.cyclops.react.async.subscription.Subscription in project cyclops by aol.
the class BatchingInvestigationsTest method streamBatch.
@Test
public void streamBatch() {
Queue<String> queue = QueueFactories.<String>unboundedQueue().build();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
queue.offer("New message " + i);
sleep(10000);
}
queue.close();
}).start();
long toRun = TimeUnit.MILLISECONDS.toNanos(500l);
queue.streamBatch(new Subscription(), source -> {
return () -> {
List<String> result = new ArrayList<>();
long start = System.nanoTime();
while (result.size() < 10 && (System.nanoTime() - start) < toRun) {
try {
String next = source.apply(1l, TimeUnit.MILLISECONDS);
if (next != null) {
result.add(next);
}
} catch (Queue.QueueTimeoutException e) {
}
}
if (result.size() > 0) {
System.out.println("Result " + result);
}
start = System.nanoTime();
return result;
};
}).filter(l -> l.size() > 0).to(s -> new LazyReact(ThreadPools.getSequential()).fromStream(s)).async().peek(System.out::println).run();
while (true) {
}
}
use of com.oath.cyclops.react.async.subscription.Subscription in project cyclops by aol.
the class Queue method streamGroupedBySizeAndTime.
public ReactiveSeq<Seq<T>> streamGroupedBySizeAndTime(int size, long time, TimeUnit t) {
long toRun = t.toNanos(time);
return streamBatch(new Subscription(), source -> {
return () -> {
List<T> result = new ArrayList<>();
long start = System.nanoTime();
try {
while (result.size() < size && checkTime(System.nanoTime(), start, toRun)) {
try {
T next = source.apply(100l, TimeUnit.MICROSECONDS);
if (next != null) {
result.add(next);
}
} catch (Queue.QueueTimeoutException e) {
}
}
} catch (Queue.ClosedQueueException e) {
if (result.size() > 0) {
List list = new ArrayList<>();
list.add(result);
throw new ClosedQueueException(list);
}
}
return result;
};
}).filter(l -> l.size() > 0).map(Seq::fromIterable);
}
Aggregations