Skip to content

Commit

Permalink
Cleanup objectpool global/local case
Browse files Browse the repository at this point in the history
Can use a ThreadLocal<ConcurrentBag> even though that makes little
sense but we only use that in tests, and it keeps the codepaths
simple.

I'd like to use Smooth.Pools now but I don't see how to get this
kind of behavior around it.

Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
  • Loading branch information
lamont-granquist committed May 10, 2023
1 parent f0e960a commit d57bc20
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions MechJeb2/MechJebLib/Utils/ObjectPool.cs
Expand Up @@ -8,7 +8,6 @@

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace MechJebLib.Utils
Expand All @@ -28,8 +27,10 @@ public class ObjectPool<T> : ObjectPoolBase
private readonly Func<T> _newfun;
private readonly Action<T>? _clearfun;

private readonly ConcurrentBag<T> _globalPool = new ConcurrentBag<T>();
private static readonly ThreadLocal<Stack<T>> _localPool = new ThreadLocal<Stack<T>>(() => new Stack<T>());
private readonly ConcurrentBag<T> _globalPool = new ConcurrentBag<T>();
private static readonly ThreadLocal<ConcurrentBag<T>> _localPool = new ThreadLocal<ConcurrentBag<T>>(() => new ConcurrentBag<T>());

private ConcurrentBag<T> _pool => UseGlobal ? _globalPool : _localPool.Value;

public ObjectPool(Func<T> newfun)
{
Expand All @@ -45,20 +46,13 @@ public ObjectPool(Func<T> newfun, Action<T> clearfun)

public T Get()
{
if (UseGlobal)
return _globalPool.TryTake(out T item) ? item : _newfun();
else
return _localPool.Value.TryPop(out T item) ? item : _newfun();
return _pool.TryTake(out T item) ? item : _newfun();
}

public void Return(T item)
{
_clearfun?.Invoke(item);

if (UseGlobal)
_globalPool.Add(item);
else
_localPool.Value.Push(item);
_pool.Add(item);
}
}
}

0 comments on commit d57bc20

Please sign in to comment.