46 lines
1 KiB
C#
46 lines
1 KiB
C#
using System;
|
|
using System.Threading;
|
|
using JD.Collections.Details;
|
|
using JD.Kernel.Classes;
|
|
|
|
namespace JD.Serializers
|
|
{
|
|
public class StringRecycler : Singleton<StringRecycler>
|
|
{
|
|
private readonly object m_lock = new object();
|
|
private readonly FastHash<string> m_strings = new FastHash<string>();
|
|
private int m_usageCount;
|
|
|
|
public IDisposable Use()
|
|
{
|
|
Interlocked.Increment(ref m_usageCount);
|
|
return new DisposableHelper(Unuse);
|
|
}
|
|
|
|
private void Unuse()
|
|
{
|
|
if (Interlocked.Decrement(ref m_usageCount) == 0)
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_strings.Clear();
|
|
}
|
|
}
|
|
}
|
|
|
|
public string Intern(string value)
|
|
{
|
|
if (value == null || m_usageCount == 0)
|
|
{
|
|
return value;
|
|
}
|
|
|
|
lock (m_lock)
|
|
{
|
|
m_strings.TryAdd(ref value);
|
|
}
|
|
|
|
return value;
|
|
}
|
|
}
|
|
}
|