标签:ar art 代码 html bs ef line new size
我们在写高效服务时,许多需要缓存,一般缓存组件都需要加锁,我最近想了一个方法,感觉还不错,分享一下。直接上代码:
public abstract class SimpleObjPool<T> { int _locker = 0; int _cnt = 0; T[] _ts; public SimpleObjPool(int MaxSize) { _ts = new T[MaxSize]; } protected abstract T NewObj(); public T GetObj() { int a = Interlocked.Exchange(ref _locker, 1); if (a == 0) { if (_cnt > 0) { _cnt--; T t = _ts[_cnt]; Interlocked.Exchange(ref _locker, 0); return t; } Interlocked.Exchange(ref _locker, 0); } return NewObj(); } public virtual bool FreeObj(T t) { int a = Interlocked.Exchange(ref _locker, 1); if (a == 0) { if (_cnt < _ts.Length) { _ts[_cnt] = t; _cnt++; Interlocked.Exchange(ref _locker, 0); return true; } Interlocked.Exchange(ref _locker, 0); } return false; } }
标签:ar art 代码 html bs ef line new size
原文地址:http://www.cnblogs.com/youkebing/p/3996529.html