I was working a program, and decided to use the new Streams API for Java 8. However, my program stopped working when I introduced .parallel()
. Here's the relevant code:
import java.math.BigInteger;
import java.util.Objects;
import java.util.stream.Stream;
import com.google.common.cache.*;
public class Alg196 {
public static void main(String[] args) {
// Add .parallel() where suitable
long c = Stream
.iterate(BigInteger.valueOf(101), i -> i.add(BigInteger.ONE))
.limit(100000000).map(BigInteger::toString).map(Alg196::alg196)
.filter(Objects::nonNull).count();
System.err.println(c);
}
private static final String reverse(String n) {
return new StringBuilder(n).reverse().toString();
}
private static final boolean isPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
private static final String alg196(String n) {
System.err.println("PROCESSING " + n);
int loops = 0;
while (!isPalindrome(n)) {
n = new BigInteger(n).add(new BigInteger(reverse(n))).toString();
loops++;
if (loops >= 100) {
return null;
}
}
if (loops <= 10) {
return null;
}
return n;
}
}
The output will contain many PROCESSING <x>
lines when working correctly, but that never happens with .parallel()
. Why is this?