Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix potential race conditions in ModelObjectPool #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Rebus.RabbitMq/Internals/ModelObjectPool.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
using RabbitMQ.Client;

namespace Rebus.Internals;
Expand All @@ -14,6 +15,7 @@ class ModelObjectPool : IDisposable
readonly WriterModelPoolPolicy _policy;

int _maxEntries;
int _currentCount = 0;

public ModelObjectPool(WriterModelPoolPolicy policy, int maxEntries)
{
Expand All @@ -26,12 +28,22 @@ public void SetMaxEntries(int maxEntries)
_maxEntries = maxEntries;
}

public IModel Get() => _availableObjects.TryTake(out var model) ? model : _policy.Create();
public IModel Get()
{
if (_availableObjects.TryTake(out var model))
{
Interlocked.Decrement(ref _currentCount);
return model;
}

return _policy.Create();
}

public void Return(IModel model)
{
if (_availableObjects.Count >= _maxEntries)
if (Interlocked.Increment(ref _currentCount) > _maxEntries)
{
Interlocked.Decrement(ref _currentCount);
model.SafeDrop();
}
else
Expand Down