I have written following sample program using sync.RWMutex.
package main
import (
"fmt"
"sync"
"time"
)
// SessionData : capture session id and cc-request-number
type SessionData struct {
id string
reqNo string
}
// SessionCache : cache for the SessionData
type SessionCache struct {
sess map[SessionData]bool
sync.RWMutex
}
// InitSessionCache : Init for SessionCache
func InitSessionCache() SessionCache {
return SessionCache{sess: make(map[SessionData]bool)}
}
// Read : read value from session cache
func (s *SessionCache) Read(sd SessionData) bool {
s.RLock()
defer s.RUnlock()
_, found := s.sess[sd]
return found
}
func (s *SessionCache) Write(sd SessionData) {
s.Lock()
defer s.Unlock()
fmt.Println("Entry not found for ", sd.id, sd.reqNo, "Creating the entry now")
s.sess[sd] = true
}
func (s *SessionCache) chkDuplicate(sessionID string, Reqno string) bool {
sd := SessionData{
id: sessionID,
reqNo: Reqno,
}
found := s.Read(sd)
if !found {
s.Write(sd)
return found
}
return found
}
func main() {
mySessionData := InitSessionCache()
for i := 0; i < 10; i++ {
go mySessionData.chkDuplicate("session1", "1")
go mySessionData.chkDuplicate("session1", "1")
go mySessionData.chkDuplicate("session1", "2")
go mySessionData.chkDuplicate("session1", "2")
go mySessionData.chkDuplicate("session1", "4")
go mySessionData.chkDuplicate("session1", "2")
}
time.Sleep(300)
fmt.Println(mySessionData)
}
when I run this program in playground https://play.golang.org/p/g93UtVxZ2dl I see that it is working correctly as the write happens only 3 times for the unique values.
Entry not found for session1 1 Creating the entry now
Entry not found for session1 2 Creating the entry now
Entry not found for session1 4 Creating the entry now
{map[{session1 1}:true {session1 2}:true {session1 4}:true] {{0 0} 0 0 0 0}}
however when I run the same program from my windows 10 machine (on VS Code) I see following output.
Entry not found for session1 1 Creating the entry now
Entry not found for session1 2 Creating the entry now
Entry not found for session1 2 Creating the entry now
Entry not found for session1 2 Creating the entry now
Entry not found for session1 4 Creating the entry now
{map[{session1 1}:true {session1 2}:true {session1 4}:true] {{0 0} 0 0 0 0}}
Am I doing something wrong? Why does this behaves differently on my Machine and Playground?