Thread safe object pool, is this object pool thread safe? If many threads Borrow() and Return() an instance of Packet from/to PacketPool could the Exception in Packet.Init() ever be thrown? Assuming only PacketPool ever called the Init() and UnInit() methods on a Packet.

class PacketPool
{
    private Stack&lt;Packet&gt; pool;

    public PacketPool(int initalNum)
    {
        pool = new Stack&lt;Packet&gt;(initalNum);

        for (int i = 0; i &lt; initalNum; i++)
        {
            Packet p = new Packet();
            pool.Push(p);
        }
    }

    public Packet Borrow()
    {
        Packet p;

        lock (pool)
        {
            if (pool.Count == 0)
            {
                p = new Packet();
            }
            else
            {
                p = pool.Pop();
            }
        }

        p.Init();

        return p;
    }

    public void Return(Packet p)
    {
        p.UnInit();

        lock (pool)
        {
            pool.Push(p);
        }
    }
}

class Packet
{
    bool isInitialized;

    public void Init()
    {
        if(isInitialized)
            throw new InvalidOperationException("Already initialized!");
        isInitialized = true;
    }

    public void UnInit()
    {
        isInitialized = false;
    }
}
Assuming only PacketPool ever called the Init() and UnInit() methods on a Packet.


I think that's not an assumption you should make. If the user of your code shouldn't call some methods, then don't let him do it, don't just assume that he won't.

What you could do is to return a facade to Packet that doesn't contain the two methods, instead of returning Packet directly.