view Implab/SafePool.cs @ 63:908b4f340c69

fixed: JSONXmlReader.Value returns invalid textual representation for numbers.
author cin
date Mon, 23 Jun 2014 17:34:40 +0400
parents 90069a2ec20a
children
line wrap: on
line source

using Implab.Parallels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Implab {
    public class SafePool<T> where T : new() {
        readonly MTQueue<T> m_queue = new MTQueue<T>();
        readonly int m_size;
        int m_count = 0;

        public SafePool() : this(10) {

        }

        public SafePool(int size) {
            Safe.ArgumentInRange(size,1,size,"size");

            m_size = size;
        }

        public T Allocate() {
            T instance;
            if (m_queue.TryDequeue(out instance)) {
                Interlocked.Decrement(ref m_count);
                return instance;
            }
            return new T();
        }

        public void Release(T instance) {
            if (m_count < m_size) {
                Interlocked.Increment(ref m_count);
                m_queue.Enqueue(instance);
            }
        }
    }
}