Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
U
utils
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
golang kittool
utils
Commits
92e3da8e
Commit
92e3da8e
authored
Apr 06, 2022
by
feidy
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add Auto Gc Map
parent
23c65280
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
94 additions
and
0 deletions
+94
-0
auto_gc_map.go
auto_gc_map.go
+77
-0
auto_gc_map_test.go
auto_gc_map_test.go
+17
-0
No files found.
auto_gc_map.go
0 → 100644
View file @
92e3da8e
package
utils
import
(
"sync"
"time"
)
const
(
// NeverDie means value.alive() returns true forever.
NeverDie
=
0
)
type
value
struct
{
data
interface
{}
ttl
int64
//time.Second
ctime
time
.
Time
}
func
newValue
(
data
interface
{},
ttl
int64
)
*
value
{
return
&
value
{
data
:
data
,
ttl
:
ttl
,
ctime
:
time
.
Now
(),
}
}
func
(
v
*
value
)
alive
()
bool
{
return
v
.
ttl
==
NeverDie
||
time
.
Now
()
.
Before
(
v
.
ctime
.
Add
(
time
.
Duration
(
v
.
ttl
)
*
time
.
Second
))
}
type
AutoGcMap
struct
{
data
map
[
string
]
*
value
lock
*
sync
.
RWMutex
}
func
NewAutoGcMap
()
*
AutoGcMap
{
return
&
AutoGcMap
{
data
:
make
(
map
[
string
]
*
value
),
lock
:
&
sync
.
RWMutex
{},
}
}
func
(
my
*
AutoGcMap
)
set
(
key
string
,
data
interface
{},
ttl
int64
)
{
my
.
lock
.
Lock
()
defer
my
.
lock
.
Unlock
()
my
.
data
[
key
]
=
newValue
(
data
,
ttl
)
}
func
(
my
*
AutoGcMap
)
get
(
key
string
)
(
interface
{},
bool
)
{
my
.
lock
.
Lock
()
defer
my
.
lock
.
Unlock
()
if
value
,
ok
:=
my
.
data
[
key
];
ok
&&
value
.
alive
()
{
return
value
.
data
,
true
}
return
nil
,
false
}
func
(
my
*
AutoGcMap
)
Gc
()
{
my
.
lock
.
Lock
()
defer
my
.
lock
.
Unlock
()
for
key
,
value
:=
range
my
.
data
{
if
!
value
.
alive
()
{
delete
(
my
.
data
,
key
)
}
}
}
func
(
my
*
AutoGcMap
)
AutoGc
(
duration
time
.
Duration
)
{
go
func
()
{
ticker
:=
time
.
NewTicker
(
duration
)
for
{
<-
ticker
.
C
my
.
Gc
()
}
}()
}
auto_gc_map_test.go
0 → 100644
View file @
92e3da8e
package
utils
import
(
"testing"
"time"
"github.com/go-playground/assert/v2"
)
func
TestAutoGc
(
t
*
testing
.
T
)
{
m
:=
NewAutoGcMap
()
m
.
AutoGc
(
3
)
m
.
set
(
"a"
,
"b"
,
10
)
time
.
Sleep
(
10
*
time
.
Second
)
_
,
b
:=
m
.
get
(
"a"
)
assert
.
Equal
(
t
,
b
,
false
)
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment