为什么内存块没有被垃圾收集器清理? [英] Why is the memory block not cleaned by the garbage collector?

查看:434
本文介绍了为什么内存块没有被垃圾收集器清理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

import(
fmt
net / http
runtime


func handler(w http.ResponseWriter,r * http.Request){
largeMemAlloc:= make([] int,100000000)
largeMemAlloc [1] = 100 // lol
fmt.Fprintf(w,hi from handler)
runtime.GC()
}

func main(){
http.HandleFunc(/,处理程序)
http.ListenAndServe(:7777,nil)
}

一旦我访问了 http://127.0.0.1:7777 4-5次使用的内存进入GB。

它已经有4-5分钟了,内存仍然没有被操作系统所声明。为什么会发生这种情况?



我做错了什么?



编辑:在10分钟后,内存使用量下降到只有50MB。但我不明白为什么花这么长时间才能回收这块内存。我觉得我正在做一些可怕的错误。



解决方案

Go不释放内存即使通过垃圾回收(GC)回收,操作系统也会立即运行。这是一个性能改进,因为它可能再次需要内存。你没有做错什么。如果不了解未来的需求,并考虑压缩,释放和从操作系统分配内存的开销,每个GC都需要进行性能平衡。在JVM和Linux内核的上下文中,有人研究如何让操作系统提供更高效的API。用户空间OOM处理是一个更近期的,不那么雄心勃勃的Linux内核开发,当GC最需要时,它可以用于更早的发布内存。

据我所知,Go没有官方上限限制Go记忆。但是,在 Go 1.3垃圾收集器不释放服务器内存回系统,它被实验验证为9分钟(发生GC至少在2分钟+7分钟后保留内存)。

您可以通过调用 runtime.debug.FreeOSMemory(),但这通常不是一个好主意,除了调试目的。


package main

import (
        "fmt"
        "net/http"
        "runtime"
)

func handler(w http.ResponseWriter, r *http.Request) {
       largeMemAlloc := make([]int, 100000000)
       largeMemAlloc[1] = 100//lol
       fmt.Fprintf(w, "hi from handler")
       runtime.GC()
}

func main() {
       http.HandleFunc("/", handler)
       http.ListenAndServe(":7777", nil)
}

Once I visit http://127.0.0.1:7777 4-5 times the memory used goes in to GBs.

Its been around 4-5 mins and the memory is still unclaimed by the OS. Why is this happening?

What am I doing wrong?

I am compiling this in go 1.5

Edit : After 10 mins, the memory usage has gone down to just 50mb. But I dont understand why it takes so long to reclaim this block of memory. I feel like I am doing something horribly wrong.

解决方案

Go does not release memory back to the OS immediately, even if it is reclaimed via garbage collection (GC). This is a performance improvement as it may need the memory again. You are not doing anything wrong. Without limited knowledge of the future demand and considering the overhead of compacting, freeing and allocating memory from the OS, every GC needs to make this performance trade-off. There was research into making the API the OS provides for this more effective in the context of the JVM and Linux kernel. User space OOM handling is a more recent, less ambitious Linux kernel development that could be used by a GC to more early release memory when it is most needed.

As far as I know there is no official upper limit for how long Go keeps memory. However in Go 1.3 Garbage collector not releasing server memory back to system it was experimentally verified to be 9 minutes (a GC which occurs at least after 2 minutes + 7 minutes holding memory in reserve).

You can manually trigger this by calling runtime.debug.FreeOSMemory(), however this is usually not a good idea except for debugging purposes.

这篇关于为什么内存块没有被垃圾收集器清理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆