-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathParallelPiEstimator.java
More file actions
65 lines (51 loc) · 1.83 KB
/
ParallelPiEstimator.java
File metadata and controls
65 lines (51 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ParallelPiEstimator implements PiEstimator {
@Override
public double estimatePi(SimulationConfig config) {
int numThreads = config.getNumThreads();
int numTasks = config.getNumTasks();
long totalPoints = config.getTotalPoints();
long pointsPerTask = totalPoints / numTasks;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
List<Future<Long>> results = new ArrayList<>();
// Create and submit tasks
for (int i = 0; i < numTasks; i++) {
Callable<Long> task = new MonteCarloTask(pointsPerTask);
results.add(executor.submit(task));
}
long totalHits = 0;
try {
// Aggregate results
for (Future<Long> future : results) {
totalHits += future.get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
return 4.0 * totalHits / (pointsPerTask * numTasks);
}
// Inner Callable Task
private static class MonteCarloTask implements Callable<Long> {
private final long pointsToSimulate;
public MonteCarloTask(long pointsToSimulate) {
this.pointsToSimulate = pointsToSimulate;
}
@Override
public Long call() {
long hits = 0;
ThreadLocalRandom random = ThreadLocalRandom.current();
for (long i = 0; i < pointsToSimulate; i++) {
double x = random.nextDouble();
double y = random.nextDouble();
if ((x * x) + (y * y) <= 1.0) {
hits++;
}
}
return hits;
}
}
}