Skip to content

Instantly share code, notes, and snippets.

@hxzhouh

hxzhouh/main.go Secret

Created December 16, 2024 09:22
Show Gist options
  • Save hxzhouh/abd6be9ed8860e506643031bb2d446ce to your computer and use it in GitHub Desktop.
Save hxzhouh/abd6be9ed8860e506643031bb2d446ce to your computer and use it in GitHub Desktop.
weak demo weak demo
package main
import (
"fmt"
"runtime"
"strings"
"time"
"unsafe"
"weak"
)
func main() {
originalObject := "Hello, World!"
runtime.AddCleanup(&originalObject, func(s int64) {
fmt.Println("originalObject clean at: ", s)
}, time.Now().Unix())
weakPtr := weak.Make(&originalObject)
fmt.Println(fmt.Sprintf("originalObject:addr %x", &originalObject))
fmt.Println(fmt.Sprintf("weakPtr addr:%x,size:%d", weakPtr, unsafe.Sizeof(weakPtr)))
runtime.GC()
time.Sleep(1 * time.Millisecond)
value := weakPtr.Value()
if value != nil && strings.Contains(*value, originalObject) {
fmt.Println("First GC :value: ", *value)
} else {
fmt.Println("first gc. Weak reference value is nil")
}
runtime.GC()
time.Sleep(1 * time.Millisecond)
value = weakPtr.Value()
if value != nil {
fmt.Println("Second GC", *value)
} else {
fmt.Println("Second GC: Weak reference value is nil")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment