Skip to content

Instantly share code, notes, and snippets.

@hide1202
Last active January 28, 2016 11:22
Show Gist options
  • Save hide1202/25d74b89e8f63a60839c to your computer and use it in GitHub Desktop.
Save hide1202/25d74b89e8f63a60839c to your computer and use it in GitHub Desktop.
namespace DotNetty.Buffers.Tests
{
using System.Threading.Tasks;
using Common;
using Xunit;
public class PooledByteBufferAllocatorTests
{
[Fact]
public void TestRelease()
{
bool isSameObject = true;
var obj = RecycleObject.NewInstance();
for (int i = 0; i < 100; i++)
{
RecycleObject prevObject = obj;
Task.Factory.StartNew(() =>
{
// If you release object in another thread,
// return value of Release method is false.
// Because Release method include follwing code.
// <code>
// Stack stack = this.Stack;
// if (stack.Thread != Thread.CurrentThread)
// {
// return false;
// }
// </code>
Assert.True(obj.Release());
}).Wait();
obj = RecycleObject.NewInstance();
// ThreadLocalPool of RecycleObject has only one object.
// So new instance from this pool, must be same.
if (obj != prevObject)
{
isSameObject = false;
break;
}
}
Assert.True(isSameObject);
}
private class RecycleObject
{
private static ThreadLocalPool<RecycleObject> pool =
new ThreadLocalPool<RecycleObject>(handle =>
new RecycleObject(handle), 1, true);
private ThreadLocalPool.Handle _handle;
public RecycleObject(ThreadLocalPool.Handle handle)
{
_handle = handle;
}
public static RecycleObject NewInstance()
{
return pool.Take();
}
public bool Release()
{
return _handle.Release(this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment