Not an absolutely bad idea, but you need a careful understanding before using sync Pool.
Golang sync Pool is used to create a self-managed object pool, with just
New/Get/Set functions. The Pool implementation uses a mutex based locking for thread-safe operations from multiple Go routines.
- Golang sync. Pool use garbage collection to manage objects. The pool is essentially a list of user-defined blob objects that are GC’ed periodically.
- The application uses
Get/Putfor using an object from the Pool.
- The application defines a
Newmethod to create a new object.
- The application does not bother about object memory management.
- Unreferenced that is objects present in the Pool at a given time is GC’ed.
- There is no finalizer for objects deletion.
Getrandomly selected object from the list; if no object is available, creates a new object and returns it.
Putplaces an object back to the Pool.
- The design wants to avoid hotspots and randomize object selections in
Getoperations. So, Put and Get calls may not be co-related.
Putop may randomly return without placing the object back to the Pool.
- This intentional delay helps the
Getto pick a new object.
What are Potential Problems with Pool
- If the object has allocated resources (socket, buffer), there is no way to free them!
- If the application has got an object and starts processing it with async operations, there is a risk of data corruption if the application returns the object to the Pool.
Best Use cases for Pool
- Plain buffer management
- Non-composite objects lifecycle management
Not to Use If
- Objects that dynamically allocate resources (buffer, sockets)
- Objects that are processed asynchronously.