Fix startAutoCloseIdleConnections cause goroutine leak #1011
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
In the submission of #999, if a connection idle time exceeds
ConnMaxLifetime
, the connection will be closed, thus introducing the following code:But this code is seriously bugged because
defer ticker.Stop()
will NEVER be executed, and thefor
loop will NEVER exit! Therefore, every time a new connection is created using theOpen
function, a new goroutine is created and can never be destroyed.My test code is as follows:
I create
100
connections and close them without doing anything, but there are still100
goroutines left that cannot be destroyed.The code execution result is as follows:
# go run main.go Running goroutine: 100 final goroutine: 100
If connections can be created successfully, more professional developers will maintain a pool of connections, which usually does not result in unlimited growth of connections, and goroutine leakage is manageable. But if the
Open
call succeeds and thePing
fails, then the goroutine is out of control forever.For example, to connect to clickhouse in a scheduled task, and then process some business logic, but the connection fails, there will be an infinite number of coroutines, which cannot be destroyed unless you restart your program.
My PR will fix #999 goroutines leak problem, when the
Close
function is invoked, to signalstartAutoCloseIdleConnections
function exit.Checklist