Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Improved the quality of randomness used for sampling.

The previous version had issues with rapidly creating and disposing of StatsdPipe instances.

If, say, 100 were created in the same millisecond, they would all be given the same Random seed.

In this version, we use ThreadStatic storage to reduce the number of Random instances created, maintain thread safety, and allow randomness to vary much more quickly that per-millisecond.
  • Loading branch information...
commit da8d73b7c6e5f51c97681964773b5fe357c7608b 1 parent a98c905
@otac0n otac0n authored
Showing with 12 additions and 2 deletions.
  1. +12 −2 examples/csharp_example.cs
View
14 examples/csharp_example.cs
@@ -8,7 +8,17 @@ namespace Statsd
public class StatsdPipe : IDisposable
{
private readonly UdpClient udpClient;
- private readonly Random random = new Random();
+
+ [ThreadStatic]
+ private static Random random;
+
+ private static Random Random
+ {
+ get
+ {
+ return random ?? (random = new Random());
+ }
+ }
public StatsdPipe(string host, int port)
{
@@ -101,7 +111,7 @@ protected bool Send(double sampleRate, params string[] stats)
{
foreach (var stat in stats)
{
- if (random.NextDouble() <= sampleRate)
+ if (Random.NextDouble() <= sampleRate)
{
var statFormatted = String.Format("{0}|@{1:f}", stat, sampleRate);
if (DoSend(statFormatted))
Please sign in to comment.
Something went wrong with that request. Please try again.