title: thread safe way of calculating moving average
body: <p>I have a library which makes HTTP calls to my service. I was trying to calculate running average of how much time my service is taking on an average.</p>
  
  <p>Here is the core logic of how I am calculating "running average".</p>
  
  <pre><code>import java.math.BigDecimal;
  import java.math.RoundingMode;
  import java.util.LinkedList;
  import java.util.Queue;
  
  public class MovingAverage {
  
      private final Queue&lt;BigDecimal&gt; window = new ArrayDeque&lt;BigDecimal&gt;();
      private final int period;
      private BigDecimal sum = BigDecimal.ZERO;
  
      public MovingAverage(int period) {
          this.period = period;
      }
  
      public void add(BigDecimal num) {
          sum = sum.add(num);
          window.add(num);
          if (window.size() &gt; period) {
              sum = sum.subtract(window.remove());
          }
      }
  
      public BigDecimal getAverage() {
          if (window.isEmpty()) return BigDecimal.ZERO;
          BigDecimal divisor = BigDecimal.valueOf(window.size());
          return sum.divide(divisor, 2, RoundingMode.HALF_UP);
      }
  }
  </code></pre>
  
  <p>Is this code thread safe because this is being called from multithreaded program? If not how can I make this multithreaded. </p>
  
  <p>I want to make sure this running average calculation is fast since this library runs under very heavy load so this should not increase the overall latency. Also I doubt I even need to use <code>BigDecimal</code> here, <code>double</code> or <code>long</code> might work here.</p>