Adding constructor that takes in an AtomicInteger argument to count the total number of prime numbers

This commit is contained in:
Thabo Ntsoko 2020-01-06 18:43:41 +02:00
parent eb1683c933
commit 1816d17cfc
2 changed files with 10 additions and 9 deletions

View File

@ -14,20 +14,21 @@ public class PrimeNumbers extends RecursiveAction {
private int granularity;
static final List<Integer> GRANULARITIES
= Arrays.asList(1, 10, 100, 1000, 10000);
private AtomicInteger noOfPrimeNumbers = new AtomicInteger();
private AtomicInteger noOfPrimeNumbers;
PrimeNumbers(int lowerBound, int upperBound, int granularity) {
PrimeNumbers(int lowerBound, int upperBound, int granularity, AtomicInteger noOfPrimeNumbers) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.granularity = granularity;
this.noOfPrimeNumbers = noOfPrimeNumbers;
}
PrimeNumbers(int upperBound) {
this(1, upperBound, 100);
this(1, upperBound, 100, new AtomicInteger(0));
}
private PrimeNumbers(int lowerBound, int upperBound) {
this(lowerBound, upperBound, 100);
private PrimeNumbers(int lowerBound, int upperBound, AtomicInteger noOfPrimeNumbers) {
this(lowerBound, upperBound, 100, noOfPrimeNumbers);
}
private List<PrimeNumbers> subTasks() {
@ -36,7 +37,7 @@ public class PrimeNumbers extends RecursiveAction {
for (int i = 1; i <= this.upperBound / granularity; i++) {
int upper = i * granularity;
int lower = (upper - granularity) + 1;
subTasks.add(new PrimeNumbers(lower, upper));
subTasks.add(new PrimeNumbers(lower, upper, noOfPrimeNumbers));
}
return subTasks;
}
@ -81,4 +82,4 @@ public class PrimeNumbers extends RecursiveAction {
public int noOfPrimeNumbers() {
return noOfPrimeNumbers.intValue();
}
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.workstealing;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
@ -11,6 +10,7 @@ import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import static org.junit.Assert.fail;
@ -59,7 +59,7 @@ public class PrimeNumbersUnitTest {
}
private void stealCountInfo(StringBuilder info, int granularity, ForkJoinPool forkJoinPool) {
PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity);
PrimeNumbers primes = new PrimeNumbers(1, 10000, granularity, new AtomicInteger(0));
forkJoinPool.invoke(primes);
forkJoinPool.shutdown();