2 * Copyright 2011 Google Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.ipc.invalidation.util;
19 import java.util.Random;
22 * An abstraction to "smear" values by a given percent. Useful for randomizing delays a little bit
23 * so that (say) processes do not get synchronized on time inadvertently, e.g., a heartbeat task
24 * that sends a message every few minutes is smeared so that all clients do not end up sending a
25 * message at the same time. In particular, given a {@code delay}, returns a value that is randomly
26 * distributed between [delay - smearPercent * delay, delay + smearPercent * delay]
29 public class Smearer {
31 private final Random random;
33 /** The percentage (0, 1.0] for smearing the delay. */
34 private double smearFraction;
37 * Creates a smearer with the given random number generator. If {@code smearPercent} is 0, uses an
38 * internal default for smearing.
40 * REQUIRES: 0 < smearPercent <= 100
42 public Smearer(Random random, final int smearPercent) {
43 Preconditions.checkState((smearPercent >= 0) && (smearPercent <= 100));
45 this.smearFraction = smearPercent / 100.0;
49 * Given a {@code delay}, returns a value that is randomly distributed between
50 * [delay - smearPercent * delay, delay + smearPercent * delay]
52 public int getSmearedDelay(int delay) {
53 // Get a random number between -1 and 1 and then multiply that by the smear
55 double smearFactor = (2 * random.nextDouble() - 1.0) * smearFraction;
56 return (int) Math.ceil(delay + delay * smearFactor);