diff --git a/stats/src/main/java/com/facebook/airlift/stats/Distribution.java b/stats/src/main/java/com/facebook/airlift/stats/Distribution.java index 32828a24c9..9ab189acd1 100644 --- a/stats/src/main/java/com/facebook/airlift/stats/Distribution.java +++ b/stats/src/main/java/com/facebook/airlift/stats/Distribution.java @@ -14,6 +14,7 @@ import java.util.Map; import static com.google.common.base.MoreObjects.toStringHelper; +import static java.util.Objects.requireNonNull; @ThreadSafe public class Distribution @@ -57,7 +58,12 @@ public synchronized void add(long value, long count) digest.add(value, count); total.add(value * count); } - + public synchronized void merge(Distribution distribution) + { + requireNonNull(distribution, "distribution is null"); + total.merge(distribution.total); + digest.merge(distribution.digest); + } @Managed public synchronized double getMaxError() { diff --git a/stats/src/test/java/com/facebook/airlift/stats/TestDistribution.java b/stats/src/test/java/com/facebook/airlift/stats/TestDistribution.java new file mode 100644 index 0000000000..7e2a603ba1 --- /dev/null +++ b/stats/src/test/java/com/facebook/airlift/stats/TestDistribution.java @@ -0,0 +1,39 @@ +package com.facebook.airlift.stats; + +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; + +public class TestDistribution +{ + @Test + public void testMerge() + { + Distribution distribution1 = new Distribution(); + Distribution distribution2 = new Distribution(); + + for (int i = 0; i < 10; i++) { + distribution1.add(i); + } + + for (int i = 10; i < 20; i++) { + distribution2.add(i); + } + + distribution1.merge(distribution2); + + assertEquals(distribution1.getP50(), 10); + assertEquals(distribution1.getMin(), 0); + assertEquals(distribution1.getMax(), 19); + assertEquals(distribution1.getCount(), 20.0); + } + + @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Expected decayCounter to have alpha.*") + public void testMergeWithIncompatibleAlphaFails() + { + Distribution distribution1 = new Distribution(0.5); + Distribution distribution2 = new Distribution(0.7); + + distribution1.merge(distribution2); + } +}