Go 会像 Java 一样受到微妙的内存泄漏的影响吗?

事实是这样的:

  • Go 语言有一个垃圾收集器。

  • Java 有一个垃圾回收

  • 很多 Java 程序都有(细微的或者没有)内存泄漏

作为一个有内存泄漏的 Java 程序的例子(不要心软,这个问题可能会动摇你的信念) ,这里介绍一个叫做 Tomcat 的小 Java 程序,它甚至有一个“查找泄漏”按钮: 有没有办法避免 Tomcat 中的未部署内存泄漏?

所以我想知道: 用 Go 编写的程序是否会出现一些用 Java 编写的程序所出现的那种(微妙的或不微妙的)内存泄漏?

14209 次浏览

You are mixing abstraction levels here: the memory leaks are due to bugs in the library (where objects reference each other though chains of 'a holds reference to b' as well as a trade-off in the implementation of the garbage collector between efficiency and accuracy. How much time do you want to spend on finding out such loops? If you spend twice as much, you'll be able to detect loops twice as long.

So the memory leak issue is not programming language specific, there is no reason that by itself GO should be better or worse than Java.

Garbage collection or not, you can write a program that has memory-leaks in Java, Go, or any other language for the most part.

Garbage Collection does take some of the burden off the programmer but it does not prevent leaks entirely.

It's very possible that Go programs will exhibit memory leaks. The current implementation of Go has a simple mark-and-sweep garbage collector. This is only intended as a temporary solution and is not intended as the long term garbage collector. See this page for more info. Look under the header Go Garbage Collector. That page even has a link to code for the current version if you are so inclined.

A 'memory leak' is when a piece of memory that the programmer thought would be freed isn't freed. This can happen in any language, garbage collected or not. The usual cause in GC languages is retaining an additional reference to the memory.

"Languages don't cause memory leaks, programmers cause memory leaks".

You are confusing different types of memory leaks here.

The heinous, explicit-memory-management based memory leaks are gone in Java (or any other GC based language). These leaks are caused by completely losing access to chunks of memory without marking them as unused.

The "memory leaks" still present in Java and every other language on the face of the planet until the computer can read our minds are still with us, and will be for the foreseeable future. These leaks are caused by the code/programmer keeping references to objects which are technically no longer needed. These are fundamentally logic bugs, and cannot be prevented in any language using current technologies.