Circular references and garbage collection

2,424 views
Skip to first unread message

Aaron Jacobs

unread,
Mar 30, 2015, 9:50:37 PM3/30/15
to golang-nuts
Hi golang-nuts,

Does the Go garbage collector have any trouble with circular references? For
example, if a struct has a function field containing a closure that refers back
to that struct, will the struct be garbage collected if it's not otherwise
referenced?

I imagine the answer is "duh, of course it will be collected", but I want to
check to be sure. Both for the current version of Go and any planned future GC
work.

Thank you,
Aaron

David Symonds

unread,
Mar 30, 2015, 10:24:23 PM3/30/15
to Aaron Jacobs, golang-nuts
Go's GC is a mark-and-sweep collector. It works fine with cycles.

Aaron Jacobs

unread,
Mar 30, 2015, 10:36:27 PM3/30/15
to David Symonds, golang-nuts
On Tue, Mar 31, 2015 at 1:24 PM, David Symonds <dsym...@golang.org> wrote:
> Go's GC is a mark-and-sweep collector. It works fine with cycles.

Great, and I'll take that to include the upcoming new collector, too.
Thanks for confirming.

djhe...@gmail.com

unread,
Mar 30, 2015, 10:40:32 PM3/30/15
to golan...@googlegroups.com
Well the following circular ref doesn't get collected: https://play.golang.org/p/zGjhGrvnPJ
If you break the circle it does: https://play.golang.org/p/9z77l64Ii3

That would lead me to believe that it has a hard time collecting circular refs, can someone comment otherwise?

Ian Lance Taylor

unread,
Mar 30, 2015, 10:44:04 PM3/30/15
to djhe...@gmail.com, golang-nuts
On Mon, Mar 30, 2015 at 7:40 PM, <djhe...@gmail.com> wrote:
>
> Well the following circular ref doesn't get collected:
> https://play.golang.org/p/zGjhGrvnPJ
> If you break the circle it does: https://play.golang.org/p/9z77l64Ii3
>
> That would lead me to believe that it has a hard time collecting circular
> refs, can someone comment otherwise?

The GC does fine at collecting circular references.

Finalizers don't work with circular references. This is documented in
the description of runtime.SetFinalizer.

Ian

djhe...@gmail.com

unread,
Mar 30, 2015, 10:45:52 PM3/30/15
to golan...@googlegroups.com, djhe...@gmail.com
Ah, thanks I missed that.
Reply all
Reply to author
Forward
0 new messages