Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does golang's garbage collector work when compiled?

I'm trying to understand how does golang's garbage collector work when the golang code is compiled and I guess when using go run as well. I figure go run is a little more straight forward and just runs the garbage collector along with the .go files you are running. But is the garbage collector compiled into the binaries as well when compiling to an executable?

like image 858
Christian Grabowski Avatar asked Aug 24 '15 15:08

Christian Grabowski


People also ask

How does the garbage collector work when does it get used?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

How does a garbage collector work internally?

In Java, garbage collection is the process of managing memory, automatically. It finds the unused objects (that are no longer used by the program) and delete or remove them to free up the memory. The garbage collection mechanism uses several GC algorithms. The most popular algorithm that is used is Mark and Sweep.

What is garbage collection How does it work explain finalize?

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.

How is garbage collector invoked?

gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector. Using Runtime. getRuntime(). gc() method: Runtime class allows the application to interface with the JVM in which the application is running.


1 Answers

The compiled object files do not contain any garbage collector "code".

When a program is run with go run, the go command will compile your sources, create and start an executable binary in a temp folder. See below.

When an application is compiled and linked into an executable binary, a go runtime is also included in the executable which is loaded when the binary is started. This runtime provides the garbage collector amongst other services such as runtime reflection and stacktrace information. This is the main reason why a simple Hello World application results in like a 2 MB executable binary.

like image 116
icza Avatar answered Sep 23 '22 07:09

icza