github.com/zhongdalu/gf@v1.0.0/g/os/gcache/gcache_cache.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gcache 8 9 import ( 10 "github.com/zhongdalu/gf/g/os/gtimer" 11 "sync/atomic" 12 "time" 13 "unsafe" 14 ) 15 16 // Cache struct. 17 type Cache struct { 18 *memCache 19 } 20 21 // New creates and returns a new cache object. 22 func New(lruCap ...int) *Cache { 23 c := &Cache{ 24 memCache: newMemCache(lruCap...), 25 } 26 gtimer.AddSingleton(time.Second, c.syncEventAndClearExpired) 27 return c 28 } 29 30 // Clear clears all data of the cache. 31 func (c *Cache) Clear() { 32 // atomic swap to ensure atomicity. 33 old := atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.memCache)), unsafe.Pointer(newMemCache())) 34 // close the old cache object. 35 (*memCache)(old).Close() 36 }