Home > Article > Backend Development > What Happens When You Forget to Cancel a Context and How to Avoid Leaks?
Impact of Failing to Cancel a Context
In the provided code snippet, a context with a 3-second timeout is created using context.WithTimeout. This context is intended to be used for an HTTP request made by the http.DefaultClient. To ensure that the resources associated with the context are released when the request completes or times out, the defer cancel statement is used.
If the defer cancel statement were omitted, the context and the goroutine it creates would be leaked. This can have significant consequences:
Memory Leak:
Performance Degradation:
How to Avoid Context Leaks:
To prevent context leaks, always call cancel when you are finished using the context. The proper way to do this is to use the defer statement immediately after calling WithCancel or WithTimeout:
ctx, cancel = context.WithTimeout(ctx, time.Duration(3) * time.Second) defer cancel()
By using defer, the cancel function will be called automatically when the surrounding function exits, ensuring that the context and its associated resources are released. This practice ensures proper memory management and prevents performance degradation due to context leaks.
The above is the detailed content of What Happens When You Forget to Cancel a Context and How to Avoid Leaks?. For more information, please follow other related articles on the PHP Chinese website!