Skip to content

fix(watch): prevent memory leak by adding StopWatch method#2039

Open
LuSrackhall wants to merge 1 commit intospf13:masterfrom
LuSrackhall:master
Open

fix(watch): prevent memory leak by adding StopWatch method#2039
LuSrackhall wants to merge 1 commit intospf13:masterfrom
LuSrackhall:master

Conversation

@LuSrackhall
Copy link

@LuSrackhall LuSrackhall commented Jul 23, 2025

Add an explicit mechanism to stop the configuration watcher and release resources.

Previously, the WatchConfig method started a goroutine that would only exit if the config file was removed or a watcher error occurred. This caused a memory leak when the Viper instance was no longer in use because the goroutine held a reference to it.

Changes:

  • Added a stopCh channel to the Viper struct to signal the watcher goroutine to exit
  • Added a public method StopWatch() that closes the stopCh channel to stop the watcher
  • Modified the goroutine in WatchConfig to listen to stopCh and exit when closed

This allows the Viper instance to be garbage collected when there are no external references and StopWatch is called.

Fixes #2038

Add an explicit mechanism to stop the configuration watcher and release resources.

Previously, the WatchConfig method started a goroutine that would only exit if the config file was removed or a watcher error occurred. This caused a memory leak when the Viper instance was no longer in use because the goroutine held a reference to it.

Changes:
- Added a `stopCh` channel to the Viper struct to signal the watcher goroutine to exit
- Added a public method `StopWatch()` that closes the `stopCh` channel to stop the watcher
- Modified the goroutine in `WatchConfig` to listen to `stopCh` and exit when closed
- Added test case to verify goroutine termination and resource cleanup

This allows the Viper instance to be garbage collected when there are no external references and StopWatch is called.

Fixes spf13#2038
@CLAassistant
Copy link

CLAassistant commented Jul 23, 2025

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory Leak : There are no publicly available methods to stop WatchConfig().

3 participants