From 3133feb0a2a15a002aea54ecf2ba86335e69f399 Mon Sep 17 00:00:00 2001 From: "jose.pedrosa" Date: Thu, 24 Aug 2017 18:39:43 +0200 Subject: [PATCH] Improve minPool size strategy to detect the maximun used connections between clean ups, and reduce the available connections to that value or min size, whatever is bigger. --- Source/MySql.Data/MySqlPool.cs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Source/MySql.Data/MySqlPool.cs b/Source/MySql.Data/MySqlPool.cs index 52148495..d601cde9 100644 --- a/Source/MySql.Data/MySqlPool.cs +++ b/Source/MySql.Data/MySqlPool.cs @@ -43,6 +43,7 @@ internal sealed class MySqlPool private bool beingCleared; private int available; private AutoResetEvent autoEvent; + private int maxUsedConnections; private void EnqueueIdle(Driver driver) { @@ -63,6 +64,7 @@ public MySqlPool(MySqlConnectionStringBuilder settings) inUsePool = new List((int)maxSize); idlePool = new Queue((int)maxSize); + maxUsedConnections = (int)minSize; // prepopulate the idle pool to minSize for (int i = 0; i < minSize; i++) EnqueueIdle(CreateNewPooledConnection()); @@ -158,6 +160,9 @@ private Driver GetPooledConnection() lock ((inUsePool as ICollection).SyncRoot) { inUsePool.Add(driver); + int currentlyInUse = inUsePool.Count; + if (currentlyInUse > maxUsedConnections) + maxUsedConnections = currentlyInUse; } return driver; } @@ -227,6 +232,7 @@ public void RemoveConnection(Driver driver) private Driver TryToGetDriver() { int count = Interlocked.Decrement(ref available); + if (count < 0) { Interlocked.Increment(ref available); @@ -310,21 +316,14 @@ internal List RemoveOldIdleConnections() // The drivers appear to be ordered by their age, i.e it is // sufficient to remove them until the first element is not // too old. - while (idlePool.Count > minSize) + int targetSize = minSize > maxUsedConnections ? (int)minSize : maxUsedConnections; + while (idlePool.Count > targetSize) { Driver d = idlePool.Peek(); - DateTime expirationTime = d.IdleSince.Add( - new TimeSpan(0, 0, MySqlPoolManager.maxConnectionIdleTime)); - if (expirationTime.CompareTo(now) < 0) - { - oldDrivers.Add(d); - idlePool.Dequeue(); - } - else - { - break; - } + oldDrivers.Add(d); + idlePool.Dequeue(); } + maxUsedConnections = (int)minSize; } return oldDrivers; }