public int TotalOutstanding {get; set;}
Console.WriteLine("Connection() - id:{0}", _id);
public static int POOL_SIZE = 100;
private static readonly Object lockPookRoundRobin = new Object();
private static Lazy<Connection>[] lazyConnection = null;
private static void InitConnectionPool()
lock (lockPookRoundRobin)
if (lazyConnection == null) {
lazyConnection = new Lazy<Connection>[POOL_SIZE];
for (int i = 0; i < POOL_SIZE; i++){
if (lazyConnection[i] == null)
lazyConnection[i] = new Lazy<Connection>(() => new Connection());
private static Connection GetLeastLoadedConnection()
Lazy<Connection> lazyContext;
var loadedLazys = lazyConnection.Where((lazy) => lazy.IsValueCreated);
if(loadedLazys.Count()==lazyConnection.Count()){
var minValue = loadedLazys.Min((lazy) => lazy.Value.TotalOutstanding);
lazyContext = loadedLazys.Where((lazy) => lazy.Value.TotalOutstanding == minValue).First();
lazyContext = lazyConnection[loadedLazys.Count()];
lazyContext.Value.TotalOutstanding = lazyContext.Value.TotalOutstanding+1;
return lazyContext.Value;
public Connection Connection
lock (lockPookRoundRobin)
return GetLeastLoadedConnection();
public static void Main()
PoolService pool = new PoolService();
for(int i=0; i<PoolService.POOL_SIZE*2; i++){
Connection connection = pool.Connection;
Console.WriteLine("Main loaded Connection - id:{0} TotalOutstanding:{1}", connection.Id, connection.TotalOutstanding);