Skip to content

Commit

Permalink
fix: Lock when using System.Random in ExponentialBackOff.
Browse files Browse the repository at this point in the history
  • Loading branch information
amanda-tarafa committed Nov 14, 2024
1 parent 3e0b9aa commit a5d793a
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions Src/Support/Google.Apis.Core/Util/ExponentialBackOff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public class ExponentialBackOff : IBackOff
private const int MaxAllowedNumRetries = 20;

/// <summary>The random instance which generates a random number to add the to next back-off.</summary>
private static readonly Random Random = new Random();
private static readonly Random s_random = new Random();
private static readonly object s_lock = new object();

/// <summary>
/// Time span used to bound the back-off jitter.
Expand Down Expand Up @@ -137,8 +138,13 @@ private int GetPercentBoundedJitter(double rawBackOffMs) =>
0 :
GetRandomBoundedValue((int)(DeltaBackOffPercent * rawBackOffMs) / 100);

private static int GetRandomBoundedValue(int upperBound) =>
Random.Next(-1 * upperBound, upperBound + 1);
private static int GetRandomBoundedValue(int upperBound)
{
lock (s_lock)
{
return s_random.Next(-1 * upperBound, upperBound + 1);
}
}

#endregion
}
Expand Down

0 comments on commit a5d793a

Please sign in to comment.