Skip to content

Instantly share code, notes, and snippets.

@mnunberg
Created November 8, 2013 19:50
Show Gist options
  • Select an option

  • Save mnunberg/7376591 to your computer and use it in GitHub Desktop.

Select an option

Save mnunberg/7376591 to your computer and use it in GitHub Desktop.
namespace Couchbase
{
internal class SocketPool : ResourcePool {
// .....
public IPooledSocket Acquire()
{
// Log..
IPooledSocket socket = null;
lock(_syncObj)
{
while (_queue.Count == 0)
{
// Releases the lock atomically,
// so a call to .Release() will not
// block
if (!Monitor.Wait(_syncObj, /* Timeout */)) {
break;
}
}
// Pool is locked again
// This should never fail. Count > 0
IPooledSocket socket = _queue.Dequeue();
}
if (socket == null) {
// Timed out
throw new TimedOutError("...");
}
// We have the Socket object from the queue.
// Whether the socket is active or not, it will
// not change membership status in the queue,
// and therefore, it's safe to execute this outside
// of a synchronized block
try {
if (!socket.IsAlive) {
socket.Close();
socket.Create();
}
return socket;
} catch (...) {
Release(socket);
throw;
}
}
public void Release(IPooledSocket socket)
{
// Log..
lock(_syncObj)
{
_queue.Enqueue(socket);
Monitor.PulseAll(_syncObj);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment