GOLANG中time.After释放的问题
来源:互联网 发布:js文件md5 编辑:程序博客网 时间:2024/06/11 10:20
原文:https://gocn.io/article/403
在谢大群里看到有同学在讨论time.After
泄漏的问题,就算时间到了也不会释放,瞬间就惊呆了,忍不住做了试验,结果发现应该没有这么的恐怖的,是有泄漏的风险不过不算是泄漏,先看API的说明:
// After waits for the duration to elapse and then sends the current time// on the returned channel.// It is equivalent to NewTimer(d).C.// The underlying Timer is not recovered by the garbage collector// until the timer fires. If efficiency is a concern, use NewTimer// instead and call Timer.Stop if the timer is no longer needed.func After(d Duration) <-chan Time { return NewTimer(d).C}
提到了一句The underlying Timer is not recovered by the garbage collector
,这句挺吓人不会被GC回收,不过后面还有条件until the timer fires
,说明fire
后是会被回收的,所谓fire
就是到时间了,写个例子证明下压压惊:
package mainimport "time"func main() { for { <- time.After(10 * time.Nanosecond) }}
显示内存稳定在5.3MB,CPU为161%,肯定被GC回收了的。当然如果放在goroutine也是没有问题的,一样会回收:
package mainimport "time"func main() { for i := 0; i < 100; i++ { go func(){ for { <- time.After(10 * time.Nanosecond) } }() } time.Sleep(1 * time.Hour)}
只是资源消耗会多一点,CPU为422%,内存占用6.4MB。因此:
Remark: time.After(d)在d时间之后就会
fire
,然后被GC回收,不会造成资源泄漏的。
那么API所说的If efficieny is a concern, user NewTimer instead and call Timer.Stop
是什么意思呢?这是因为一般time.After
会在select中使用,如果另外的分支跑得更快,那么timer是不会立马释放的(到期后才会释放),比如这种:
select { case time.After(3*time.Second): return errTimeout case packet := packetChannel: // process packet.}
如果packet非常多,那么总是会走到下面的分支,上面的timer不会立刻释放而是在3秒后才能释放,和下面代码一样:
package mainimport "time"func main() { for { select { case <-time.After(3 * time.Second): default: } }}
这个时候,就相当于会堆积了3秒的timer没有释放而已,会不断的新建和释放timer,内存会稳定在2.8GB,这个当然就不是最好的了,可以主动释放:
package mainimport "time"func main() { for { t := time.NewTimer(3*time.Second) select { case <- t.C: default: t.Stop() } }}
这样就不会占用2.8GB内存了,只有5MB左右。因此,总结下这个After的说明:
- GC肯定会回收
time.After
的,就在d之后就回收。一般情况下让系统自己回收就好了。 - 如果有效率问题,应该使用
Timer
在不需要时主动Stop。大部分时候都不用考虑这个问题的。
交作业。
- GOLANG中time.After释放的问题
- GO中time.After释放的问题
- golang time.After()
- [golang]time.After 在select中使用的正确姿势(解决超时逻辑未生效bug)
- Golang time.Parse和time.Format的时区问题
- time.After 在select-case中使用的正确姿势
- golang中time包用法
- golang中time包用法
- golang time 时间的加减法
- Golang开发中遇到的一些问题。
- golang interface实现中遇到的问题
- Golang中unsafe.Sizeof()的问题
- golang time
- time after time
- DirectShow 开发中内存释放的问题
- dockpanel中DockContent的释放问题
- 程序中出现的堆释放问题
- Delphi中对象释放的问题
- adb常用命令总结
- Deeply Learned Attributes for Crowded Scene Understanding(WWW dataset)
- qduoj 156 暴力过算我输 思维+单调栈
- dubbo源码深度解读二之config模块
- 914电路原理
- GOLANG中time.After释放的问题
- POJ1740--A New Stone Game(Nin变形)
- 算法训练 寂寞的数
- MySQL备份Percona Xtrabackup安装和卸载
- java得到指定文件大小
- 二维数组中的查找【每日一题】
- PAC4J 初探
- DPDK之初识与环境搭建
- bzoj1149: [CTSC2007]风玲Mobiles