Connection pool fragmentation
Customer reported connection pool fragmentation issue. Customer runs an Web Application, and they found 3000+ connection pools that have 0 connection for the same connection string in their memory dump.
After investigation in multi-thread environment, I could reproduce the issue, which is lots of pools created for the same connection string, and 0 connection in the pool. This happens because each thread creates new connection pool immediately after the thread cannot find target connection pool in a connection pool group in unsynchronized context: https://github.com/dotnet/corefx/blob/e7723074a7ee7cfbc1da516108d2ad85082d77d4/src/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPoolGroup.cs#L180-L197 New connection pools with 0 connection are created as many as the number of threads that check if target connection exists in the pool.
Only the logic that adds newly created connection to connection pool after duplicated check is synchronized (locked). So only one connection is added to the pool as synchronized, and the other pools are just discarded.
This is not necessarily a bug since only one connection is added to pool, and other connections are discarded properly. However, when Garbage Collector is kicked off not often enough to clean up the extra empty pools, there may be lots of empty connection pools for the same connection string reside in memory for a while.
Similar thing happens when connection pool group is created and added to connection factory. There are many extra connection pool groups created by threads for the same connection string, and only one connection pool group is added to connection factory. This also makes connection pool group fragmentation as well, which will resides in memory until Garbage Collector cleans it off. https://github.com/dotnet/corefx/blob/e7723074a7ee7cfbc1da516108d2ad85082d77d4/src/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionFactory.cs#L388-L407
This issue can be fixed by moving code part for the connection pool creation to synchronized (lock) block so that only one thread can create connection pool, and adds it to pool group. It will prevent the extra empty pool creation, which will save memory and CPU resource consumption.
The fix was merged to main branch.