-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleLeakyBucket.cs
More file actions
92 lines (80 loc) · 2.41 KB
/
Copy pathSimpleLeakyBucket.cs
File metadata and controls
92 lines (80 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency;
public class SimpleLeakyBucket : IDisposable
{
private readonly int leakInterval;
private readonly int maxBucketSize;
private readonly int outputRate;
private readonly Queue<int> queue;
private int bucketSize;
private bool disposed;
private Timer leaker;
private int locked;
public SimpleLeakyBucket(int maxBucketSize, int outputRate, int leakInterval)
{
this.outputRate = outputRate;
this.leakInterval = leakInterval;
this.maxBucketSize = maxBucketSize;
bucketSize = 0;
locked = 0;
queue = new Queue<int>();
leaker = new Timer(Leak, null, Timeout.Infinite, Timeout.Infinite);
leaker.Change(leakInterval, Timeout.Infinite);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public bool TryEnqueue(int value)
{
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
{
if (bucketSize + value > maxBucketSize)
{
Volatile.Write(ref locked, 0);
return false;
}
try
{
queue.Enqueue(value);
bucketSize += value;
return true;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
}
private void Leak(object state)
{
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
try
{
while (queue.Any() && queue.Peek() <= outputRate)
{
var output = queue.Dequeue();
bucketSize -= output;
}
leaker = new Timer(Leak, null, Timeout.Infinite, Timeout.Infinite);
leaker.Change(leakInterval, Timeout.Infinite);
return;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing) leaker.Dispose();
disposed = true;
}
}