Skip to content

Commit 0744c21

Browse files
committed
runtime: make runtime.GC() trigger GC even if GOGC=off
Currently, the priority of checks in (gcTrigger).test() puts the gcpercent<0 test above gcTriggerCycle, which is used for runtime.GC(). This is an unintentional change from 1.8 and before, where runtime.GC() triggered a GC even if GOGC=off. Fix this by rearranging the priority so the gcTriggerCycle test executes even if gcpercent < 0. Fixes #22023. Change-Id: I109328d7b643b6824eb9d79061a9e775f0149575 Reviewed-on: https://go-review.googlesource.com/65994 Run-TryBot: Austin Clements <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Rick Hudson <[email protected]>
1 parent 382d492 commit 0744c21

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/runtime/gc_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,3 +499,19 @@ func BenchmarkReadMemStats(b *testing.B) {
499499

500500
hugeSink = nil
501501
}
502+
503+
func TestUserForcedGC(t *testing.T) {
504+
// Test that runtime.GC() triggers a GC even if GOGC=off.
505+
defer debug.SetGCPercent(debug.SetGCPercent(-1))
506+
507+
var ms1, ms2 runtime.MemStats
508+
runtime.ReadMemStats(&ms1)
509+
runtime.GC()
510+
runtime.ReadMemStats(&ms2)
511+
if ms1.NumGC == ms2.NumGC {
512+
t.Fatalf("runtime.GC() did not trigger GC")
513+
}
514+
if ms1.NumForcedGC == ms2.NumForcedGC {
515+
t.Fatalf("runtime.GC() was not accounted in NumForcedGC")
516+
}
517+
}

src/runtime/mgc.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1158,7 +1158,7 @@ func (t gcTrigger) test() bool {
11581158
if t.kind == gcTriggerAlways {
11591159
return true
11601160
}
1161-
if gcphase != _GCoff || gcpercent < 0 {
1161+
if gcphase != _GCoff {
11621162
return false
11631163
}
11641164
switch t.kind {
@@ -1169,6 +1169,9 @@ func (t gcTrigger) test() bool {
11691169
// own write.
11701170
return memstats.heap_live >= memstats.gc_trigger
11711171
case gcTriggerTime:
1172+
if gcpercent < 0 {
1173+
return false
1174+
}
11721175
lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
11731176
return lastgc != 0 && t.now-lastgc > forcegcperiod
11741177
case gcTriggerCycle:

0 commit comments

Comments
 (0)