github.com/songzhibin97/gkit@v1.2.13/gctuner/finalizer_test.go (about)

     1  package gctuner
     2  
     3  import (
     4  	"runtime"
     5  	"runtime/debug"
     6  	"sync/atomic"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestFinalizer(t *testing.T) {
    13  	// disable gc
    14  	debug.SetGCPercent(-1)
    15  	defer debug.SetGCPercent(100)
    16  
    17  	maxCount := int32(16)
    18  	is := assert.New(t)
    19  	var count int32
    20  	f := newFinalizer(func() {
    21  		n := atomic.AddInt32(&count, 1)
    22  		if n > maxCount {
    23  			t.Fatalf("cannot exec finalizer callback after f has been gc")
    24  		}
    25  	})
    26  	for atomic.LoadInt32(&count) < maxCount {
    27  		runtime.GC()
    28  	}
    29  	is.Nil(f.ref)
    30  	f.stop()
    31  	// when f stopped, finalizer callback will not be called
    32  	lastCount := atomic.LoadInt32(&count)
    33  	for i := 0; i < 10; i++ {
    34  		runtime.GC()
    35  		is.Equal(lastCount, atomic.LoadInt32(&count))
    36  	}
    37  }