1// run
2
3//go:build !nacl && !js
4
5// Copyright 2011 The Go Authors. All rights reserved.
6// Use of this source code is governed by a BSD-style
7// license that can be found in the LICENSE file.
8
9// Test that buffered channels are garbage collected properly.
10// An interesting case because they have finalizers and used to
11// have self loops that kept them from being collected.
12// (Cyclic data with finalizers is never finalized, nor collected.)
13
14package main
15
16import (
17	"fmt"
18	"os"
19	"runtime"
20)
21
22func main() {
23	const N = 10000
24	st := new(runtime.MemStats)
25	memstats := new(runtime.MemStats)
26	runtime.ReadMemStats(st)
27	for i := 0; i < N; i++ {
28		c := make(chan int, 10)
29		_ = c
30		if i%100 == 0 {
31			for j := 0; j < 4; j++ {
32				runtime.GC()
33				runtime.Gosched()
34				runtime.GC()
35				runtime.Gosched()
36			}
37		}
38	}
39
40	runtime.ReadMemStats(memstats)
41	obj := int64(memstats.HeapObjects - st.HeapObjects)
42	if obj > N/5 {
43		fmt.Println("too many objects left:", obj)
44		os.Exit(1)
45	}
46}
47