Skip to content

sync: add new Map methods CompareAndSwap, CompareAndDelete, Swap #51972

Closed
@9072997

Description

@9072997

I propose adding a new method on sync.Map similar to atomic.Value's Swap() method. I think either the name LoadAndStore() to match the existing LoadOrStore or Swap() to match atomic.Value would make sense. The function signature would look something like this

func (m *Map) LoadAndStore(key, newValue any) (previous any, loaded bool)

I think the fact that this already exists in atomic.Value is a good argument that there is a use case for it. The same thing could be achieved by creating a sync.Map of atomic.Values, but that is a lot of type-assertion, and I have to stare at it pretty hard to make sure it's free of race conditions. My specific use case is basically de-bouncing abuse reports. If a worker detects abuse from a client it would

lastReport, hasReportHistory := lastReportTimes.LoadAndStore(clientIP, time.Now())
if hasReportHistory && time.Since(lastReport.(time.Time)) < time.Hour {
    log("not re-sending abuse report")
    return
}
sendAbuseReport(clientIP)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions