Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created June 10, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaembo/c0e24c7dbc9f1728e638 to your computer and use it in GitHub Desktop.
Save amaembo/c0e24c7dbc9f1728e638 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class ShortCircuitTest {
static class IntShortCircuitException extends RuntimeException {
int payload;
public IntShortCircuitException(int payload) {
this.payload = payload;
}
}
public static boolean isSumGreater(IntStream stream, int limit) {
int result;
try {
result = stream.reduce(0, (a, b) -> {
int res = a + b;
if(res > limit)
throw new IntShortCircuitException(res);
return res;
});
} catch (IntShortCircuitException e) {
result = e.payload;
}
return result > limit;
}
public static void test(int[] source, int limit) {
AtomicInteger counter = new AtomicInteger();
boolean result = isSumGreater(Arrays.stream(source).parallel().peek(i -> counter.incrementAndGet()), limit);
System.out.println("Limit = "+limit+"; result = "+result+"; processed = "+counter.get());
}
public static void main(String[] args) {
int[] source = IntStream.range(0, 10000).toArray();
test(source, 10);
test(source, 100);
test(source, 1000);
test(source, 10000);
test(source, 100000);
test(source, 1000000);
test(source, 10000000);
test(source, 100000000);
}
}
Limit = 10; result = true; processed = 34
Limit = 100; result = true; processed = 2
Limit = 1000; result = true; processed = 1
Limit = 10000; result = true; processed = 29
Limit = 100000; result = true; processed = 16
Limit = 1000000; result = true; processed = 151
Limit = 10000000; result = true; processed = 2500
Limit = 100000000; result = false; processed = 10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment