Skip to content

Commit 43881aa

Browse files
authored
fix ctor rounding (#71)
1 parent 4fd889e commit 43881aa

File tree

2 files changed

+56
-5
lines changed

2 files changed

+56
-5
lines changed

BitFaster.Caching.UnitTests/Lru/ConcurrentLruTests.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,34 @@ public void WhenComparerIsNullCtorThrows()
4949
constructor.Should().Throw<ArgumentNullException>();
5050
}
5151

52+
[Fact]
53+
public void WhenCapacityIs4HotHasCapacity1AndColdHasCapacity2()
54+
{
55+
var lru = new ConcurrentLru<int, int>(4);
56+
57+
for (int i = 0; i < 5; i++)
58+
{
59+
lru.GetOrAdd(i, x => x);
60+
}
61+
62+
lru.HotCount.Should().Be(1);
63+
lru.ColdCount.Should().Be(2);
64+
}
65+
66+
[Fact]
67+
public void WhenCapacityIs5HotHasCapacity2AndColdHasCapacity2()
68+
{
69+
var lru = new ConcurrentLru<int, int>(5);
70+
71+
for (int i = 0; i < 5; i++)
72+
{
73+
lru.GetOrAdd(i, x => x);
74+
}
75+
76+
lru.HotCount.Should().Be(2);
77+
lru.ColdCount.Should().Be(2);
78+
}
79+
5280
[Fact]
5381
public void ConstructAddAndRetrieveWithDefaultCtorReturnsValue()
5482
{

BitFaster.Caching/Lru/TemplateConcurrentLru.cs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,12 @@ public TemplateConcurrentLru(
6868
if (comparer == null)
6969
{
7070
throw new ArgumentNullException(nameof(comparer));
71-
}
72-
73-
this.hotCapacity = capacity / 3;
74-
this.warmCapacity = capacity / 3;
75-
this.coldCapacity = capacity / 3;
71+
}
72+
73+
var queueCapacity = ComputeQueueCapacity(capacity);
74+
this.hotCapacity = queueCapacity.hot;
75+
this.warmCapacity = queueCapacity.warm;
76+
this.coldCapacity = queueCapacity.cold;
7677

7778
this.hotQueue = new ConcurrentQueue<I>();
7879
this.warmQueue = new ConcurrentQueue<I>();
@@ -387,5 +388,27 @@ private void Move(I item, ItemDestination where)
387388
break;
388389
}
389390
}
391+
392+
private static (int hot, int warm, int cold) ComputeQueueCapacity(int capacity)
393+
{
394+
int hotCapacity = capacity / 3;
395+
int warmCapacity = capacity / 3;
396+
int coldCapacity = capacity / 3;
397+
398+
int remainder = capacity % 3;
399+
400+
switch (remainder)
401+
{
402+
case 1:
403+
coldCapacity++;
404+
break;
405+
case 2:
406+
hotCapacity++;
407+
coldCapacity++;
408+
break;
409+
}
410+
411+
return (hotCapacity, warmCapacity, coldCapacity);
412+
}
390413
}
391414
}

0 commit comments

Comments
 (0)