| OLD | NEW |
| (Empty) | |
| 1 /* |
| 2 * Copyright 2011 Google Inc. |
| 3 * |
| 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 |
| 7 * |
| 8 * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 * |
| 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. |
| 15 */ |
| 16 |
| 17 package com.google.ipc.invalidation.util; |
| 18 |
| 19 import java.util.Random; |
| 20 |
| 21 /** |
| 22 * An abstraction to "smear" values by a given percent. Useful for randomizing d
elays 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 val
ue that is randomly |
| 26 * distributed between [delay - smearPercent * delay, delay + smearPercent * del
ay] |
| 27 * |
| 28 */ |
| 29 public class Smearer { |
| 30 |
| 31 private final Random random; |
| 32 |
| 33 /** The percentage (0, 1.0] for smearing the delay. */ |
| 34 private double smearFraction; |
| 35 |
| 36 /** |
| 37 * Creates a smearer with the given random number generator. If {@code smearPe
rcent} is 0, uses an |
| 38 * internal default for smearing. |
| 39 * <p> |
| 40 * REQUIRES: 0 < smearPercent <= 100 |
| 41 */ |
| 42 public Smearer(Random random, final int smearPercent) { |
| 43 Preconditions.checkState((smearPercent >= 0) && (smearPercent <= 100)); |
| 44 this.random = random; |
| 45 this.smearFraction = smearPercent / 100.0; |
| 46 } |
| 47 |
| 48 /** |
| 49 * Given a {@code delay}, returns a value that is randomly distributed between |
| 50 * [delay - smearPercent * delay, delay + smearPercent * delay] |
| 51 */ |
| 52 public int getSmearedDelay(int delay) { |
| 53 // Get a random number between -1 and 1 and then multiply that by the smear |
| 54 // fraction. |
| 55 double smearFactor = (2 * random.nextDouble() - 1.0) * smearFraction; |
| 56 return (int) Math.ceil(delay + delay * smearFactor); |
| 57 } |
| 58 } |
| OLD | NEW |