Last active
January 28, 2016 11:22
-
-
Save hide1202/25d74b89e8f63a60839c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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