Will this ever get garbage collected?

Issue

I have a config object which initializes some variables based on environment variables at startup:

// init the conf object on startup and fail quickly if there's an environment issue
_ = utils.GetConf()

This is in the init() method of my server, and in other places in my code, I just call GetConf() to get the config object. I’d like to implement this config object through a singleton pattern:

import (
    "fmt"

    env "github.com/Netflix/go-env"
)

type Conf struct {
    DBName        string `env:"MONGO_INITDB_DATABASE,required=true"`
    Hostname      string `env:"HOSTNAME,required=true"`
    DBUsername    string `env:"MONGO_INITDB_ROOT_USERNAME,required=true"`
    DBPassword    string `env:"MONGO_INITDB_ROOT_PASSWORD,required=true"`
}

var gConf *Conf

func GetConf() *Conf {
    if gConf != nil {
        return gConf
    }
    gConf = new(Conf)
    _, err := env.UnmarshalFromEnviron(gConf)
    if err != nil {
        panic(err)
    }
    return gConf
}

Since I’m not doing anything with the return value of utils.GetConf() at the start, is it possible that golang will garbage collect my config object and my gConf pointer will end up pointing to nowhere?

Solution

If you create a pointer to a value, dereferencing that pointer will yield that value.

That is really all you must bear in mind. The garbage collection system may be doing whatever it’s doing behind the scene, but the above statement must still remain true. If the garbage collector were to invalidate your pointers before you use them, that would be a broken implementation of the language (i.e., a compiler bug).

When in doubt about how Go works, always consult the Go language specification. You’ll see that pointer behaviour is plainly defined. Garbage collection, on the other hand, is only mentioned in the introduction without defining any behaviour. Therefore, we can assume that garbage collection should not override or otherwise interfere with the way pointers are supposed to work.

Answered By – Hymns For Disco

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.