对象池区别与其他的连接池,它只能存放临时的变量,用来缓解GC的处理压力。
用途:
1.sync.Pool是一个可以存或取的临时对象集合
2.sync.Pool可以安全被多个线程同时使用,保证线程安全
注意、注意、注意,sync.Pool中保存的任何项都可能随时不做通知的释放掉,所以不适合用于像socket长连接或数据库连接池。
sync.Pool主要用途是增加临时对象的重用率,减少GC负担。
type Pool struct {
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() interface{}
// contains filtered or unexported fields
}
//从 Pool 中获取元素,元素数量 -1,当 Pool 中没有元素时,会调用 New 生成元素,新元素不会放入 Pool 中,若 New 未定义,则返回 nil
func (p *Pool) Get() interface{}
//往 Pool 中添加元素 x
func (p *Pool) Put(x interface{})
package main
import (
"sync"
"net"
"fmt"
"runtime"
)
func main() {
sp2 := sync.Pool{
New: func() interface{} {
conn, err := net.Dial("tcp", "127.0.0.1:8888");
if err != nil {
return nil
}
return conn
},
}
buf := make([]byte, 1024)
//获取对象
conn := sp2.Get().(net.Conn)
//使用对象
conn.Write([]byte("GET / HTTP/1.1 \r\n\r\n"))
n, _ := conn.Read(buf)
fmt.Println("conn read : ", string(buf[:n]))
//打印conn的地址
fmt.Println("coon地址:",conn)
//把对象放回池中
sp2.Put(conn)
//我们人为的进行一次垃圾回收
runtime.GC()
//再次获取池中的对象
conn2 := sp2.Get().(net.Conn)
//这时发现conn2的地址与上面的conn的地址不一样了
//说明池中我们之前放回的对象被全部清除了,显然这并不是我们想看到的
//所以sync.Pool不适合用于scoket长连接或数据库连接池
fmt.Println("coon2地址",conn2)
}