Skip to content

proposal: sync: Allow (*sync.Map).LoadOrStore uses closure to create new value like sync.Pool #44159

Closed
@ethe

Description

@ethe

Currently, LoadOrStore only allows passing a value directly, however, considering this case:

var smap sync.Map

// creating value needs a factory function
// maybe a heavy overhead initialization function
// always initialized even there has been an object loaded from the below map
bar := NewValue()
smap.LoadOrStore("foo", bar) 

if I want to avoid this initialization every time, I have to give up using LoadOrStore or combine it and sync.Pool: implement the lazy initialization when there is not an existing value be loaded:

var smap sync.Map

bar := valuePool.Get().(*Bar)
bar, loaded := smap.LoadOrStore("foo", bar)
if !loaded {
    bar.Init()
} else {
    valuePool.Put(bar)
}

if there is a way to put a New closure into LoadOrStore function, maybe like:

func (m *Map) LoadOrStoreFrom(key interface{}, newValue func() interface{}) (actual interface{}, loaded bool)

it may reduce tons of overhead in this case, and I think the above case is common to meet.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions