I'm writting a small parallel program for computing the value of e
. I don't get why some values in the array are null if all the tasks in the thread pool are finished. Any help on clarifing where the problem is, is welcomed. Code is bellow:
import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class main {
private static BigDecimal [] taylorSeriesMemebers;
public static void main(String[] args) {
int seriesSize = 20;
int threadCount = 6;
taylorSeriesMemebers = new BigDecimal[seriesSize];
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
for(int i = 0 ; i < seriesSize ; i++) {
int k = i;
threadPool.submit(() -> {
calculateMember(k);
});
}
threadPool.shutdown();
while(!threadPool.isTerminated()) {
}
System.out.println("All tasks finished");
BigDecimal answer = BigDecimal.ZERO;
for(BigDecimal bd : taylorSeriesMemebers) {
answer = answer.add(bd);
}
System.out.println(answer.toString());
}
private static void calculateMember(int k) {
BigDecimal first = new BigDecimal(k*2 + 1);
BigDecimal second = bigFactoriel(2*k);
BigDecimal divided = first.divide(second);
taylorSeriesMemebers[k] = divided;
}
private static BigDecimal bigFactoriel(int k) {
BigDecimal factNumber = BigDecimal.ONE;
if ( k < 2 ) {
return factNumber;
}
for(int i = 2; i <= k; i++) {
factNumber = factNumber.multiply(new BigDecimal(i));
}
return factNumber;
}
}
The exception
All tasks finished
Exception in thread "main" java.lang.NullPointerException
at java.math.BigDecimal.add(Unknown Source) // <-- in the for loop
at test.main.main(main.java:37)
The problem is the call of divide
, you have to change it to:
BigDecimal divided = first.divide(second, MathContext.DECIMAL128);
There does a ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result” appear.