DoubleAdder Sums Floating Values
Accumulate double samples with DoubleAdder, read sumThenReset, and compare the running total with doubleValue after many adds.
Code
import java.util.concurrent.atomic.DoubleAdder;
public class Main {
public static void main(String[] args) {
DoubleAdder weights = new DoubleAdder();
// add sums floating-point samples without one shared volatile
weights.add(0.1);
weights.add(0.2);
weights.add(0.3);
System.out.println("sum: " + weights.sum());
// sumThenReset returns the total and clears the accumulator
double total = weights.sumThenReset();
System.out.println("total: " + total);
System.out.println("after reset: " + weights.sum());
for (int i = 1; i <= 1000; i++) {
weights.add(0.001);
}
System.out.println("thousand adds: " + weights.sum());
System.out.println("double check: " + weights.doubleValue());
}
}How the snippet works
Everything happens inside the class Main and the function main.
The file repeats itself only inside for (int i = 1; i <= 1000; i++).
What to watch for
- The imports (if any) point only at standard-library modules.
Applying it
The main signature reads public static void main(String[] args)
Each run prints the 3 labeled blocks sum:, total:, after reset: in source order.
Statements that matter
DoubleAdder weights = new DoubleAdder();
double total = weights.sumThenReset();
weights.add(0.001);
Interactive Tools for This Topic
FAQ
- What does DoubleAdder Sums Floating Values print when run?
- Execute the whole file; each printed line is prefixed with a label like `sum:`, `total:`, `after reset:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.