Sync Map may cause an increase in ram and goroutine
php editor Youzi reminds you that using Sync Map may lead to an increase in RAM and goroutine. Sync Map is a library in Go language used to implement concurrency-safe mapping data structures. Although it provides efficient performance when handling concurrent reads and writes, using Sync Map may lead to an increase in memory usage and the number of goroutines when processing large-scale data. Therefore, when using Sync Map, you need to weigh the balance between usage and performance based on specific business scenarios and needs to ensure the stability and efficiency of the system.
Question content
Hello, this is the code where I call util a collector
import ( "context" "errors" "sync" "time" ) type Collector struct { keyValMap *sync.Map } func (c *Collector) LoadOrWait(key any) (retValue any, availability int, err error) { value, status := c.getStatusAndValue(key) switch status { case 0: return nil, 0, nil case 1: return value, 1, nil case 2: ctxWithTimeout, _ := context.WithTimeout(context.Background(), 5 * time.Second) for { select { case <-ctxWithTimeout.Done(): return nil, 0, errRequestTimeout default: value, resourceStatus := c.getStatusAndValue(key) if resourceStatus == 1 { return value, 1, nil } time.Sleep(50 * time.Millisecond) } } } return nil, 0, errRequestTimeout } // Store ... func (c *Collector) Store(key any, value any) { c.keyValMap.Store(key, value) } func (c *Collector) getStatusAndValue(key any) (retValue any, availability int) { var empty any result, loaded := c.keyValMap.LoadOrStore(key, empty) if loaded && result != empty { return result, 1 } if loaded && result == empty { return empty, 2 } return nil, 0 }
So the purpose of this utility is to act as a cache where similar values are loaded only once but read multiple times. However, when the collector's object is passed to multiple goroutines, I face increased gorotine and ram usage whenever multiple goroutines try to use the collector cache. Can someone explain if this usage of synchronized maps is correct. If yes, then what may be the reason for the high number of goroutines/high memory usage
Solution
Of course, since the cancellation function of the newly created ctxwithtimeout
context is not called , you may face memory leaks. To resolve this issue, change the line to:
ctxWithTimeout, cancelFunc := context.WithTimeout(context.Background(), requestTimeout) defer cancelFunc()
So you can always clear all allocated resources once the context expires. This should resolve the leak.
Regarding the usage of sync.map
it seems fine to me.
If this solves your problem or there are other issues that need to be solved, please let me know, thank you!
The above is the detailed content of Sync Map may cause an increase in ram and goroutine. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...
