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<Packet> pool;
public PacketPool(int initalNum)
{
pool = new Stack<Packet>(initalNum);
for (int i = 0; i < 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;
}
}