Created
June 10, 2015 08:39
-
-
Save amaembo/c0e24c7dbc9f1728e638 to your computer and use it in GitHub Desktop.
This file contains 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
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); | |
} | |
} |
This file contains 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
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