Comments on: Fixing a Memory Leak in Go: Understanding time.After https://arangodb.com/2020/09/a-story-of-a-memory-leak-in-go-how-to-properly-use-time-after/ The database for graph and beyond Wed, 26 Jun 2024 07:52:45 +0000 hourly 1 https://wordpress.org/?v=6.7.1 By: Laura Cope https://arangodb.com/2020/09/a-story-of-a-memory-leak-in-go-how-to-properly-use-time-after/#comment-31 Fri, 31 Mar 2023 13:23:50 +0000 https://arangodb.com/?p=35186#comment-31 In reply to Todd.

yes, the below line:
go func() { <-timeout }() // prevent leak
could also work, but it creates a separate go-routine which eventually will be finished depends on the timeout variable.
When the timeout variable was high then go-routine would exist during this timeout, which is not good for a performance. It is better to close a timer when we know that it is not longer required.

]]>
By: Todd https://arangodb.com/2020/09/a-story-of-a-memory-leak-in-go-how-to-properly-use-time-after/#comment-30 Thu, 16 Feb 2023 20:47:05 +0000 https://arangodb.com/?p=35186#comment-30 couldn’t you also do

“`
timeout := time.After(time.Second)
select {
  case <-timeout:
// do something after 1 second.
  case <-ctx.Done():
go func() { <-timeout }() // prevent leak
// do something when context is finished.
  }
“`

]]>