I am using goroutines in a package where there is a tcp server. The response most of the time is very heavy, but when the routines end it is not cleared from the memory.
func Handle() {
service := ":7777"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
defer listener.Close()
for {
conn, err := listener.Accept()
checkError(err)
go handleRequest(conn, db)
}
}
func handleRequest(conn net.Conn, db *sql.DB) {
message := make([]byte, 0, 4096)
tmp := make([]byte, 256)
n, err := conn.Read(tmp)
if err != nil {
if err != io.EOF {
fmt.Println("read error:", err)
}
}
message = append(message, tmp[:n]...)
fmt.Println("Message Received:", string(message))
// do something to get resp
conn.Write(append(resp, []byte("\n")...))
conn.Close()
debug.FreeOSMemory()
return
}
So in this case the response is big, and a goroutine using 10% of the memory, thats okay, because I'm getting 170.000 users from the database and parse the result to JSON. But when the handleRequest and it is still in the memory, if I'm not using debug.FreeOsMemory()
. I have doubts it is a good way to do it because it is in the debug pacakge so my question is it a good way to empty the memory what the goroutines are using? I tested it so it is not affected to the system and working very well. If not, what is the good way? I can't wait the GC for clear it up?! I read this and this is why I started to use it, in the first answer there is the last suggestion.