| 34 | } |
| 35 | |
| 36 | func TestNew(t *testing.T) { |
| 37 | // Disable GC to avoid the victim cache during the test. |
| 38 | defer debug.SetGCPercent(debug.SetGCPercent(-1)) |
| 39 | |
| 40 | p := pool.New(func() *pooledValue[string] { |
| 41 | return &pooledValue[string]{ |
| 42 | value: "new", |
| 43 | } |
| 44 | }) |
| 45 | |
| 46 | // Probabilistically, 75% of sync.Pool.Put calls will succeed when -race |
| 47 | // is enabled (see ref below); attempt to make this quasi-deterministic by |
| 48 | // brute force (i.e., put significantly more objects in the pool than we |
| 49 | // will need for the test) in order to avoid testing without race enabled. |
| 50 | // |
| 51 | // ref: https://cs.opensource.google/go/go/+/refs/tags/go1.20.2:src/sync/pool.go;l=100-103 |
| 52 | for i := 0; i < 1_000; i++ { |
| 53 | p.Put(&pooledValue[string]{ |
| 54 | value: t.Name(), |
| 55 | }) |
| 56 | } |
| 57 | |
| 58 | // Ensure that we always get the expected value. Note that this must only |
| 59 | // run a fraction of the number of times that Put is called above. |
| 60 | for i := 0; i < 10; i++ { |
| 61 | func() { |
| 62 | x := p.Get() |
| 63 | defer p.Put(x) |
| 64 | require.Equal(t, t.Name(), x.value) |
| 65 | }() |
| 66 | } |
| 67 | |
| 68 | // Depool all objects that might be in the pool to ensure that it's empty. |
| 69 | for i := 0; i < 1_000; i++ { |
| 70 | p.Get() |
| 71 | } |
| 72 | |
| 73 | // Now that the pool is empty, it should use the value specified in the |
| 74 | // underlying sync.Pool.New func. |
| 75 | require.Equal(t, "new", p.Get().value) |
| 76 | } |
| 77 | |
| 78 | func TestNew_Race(t *testing.T) { |
| 79 | p := pool.New(func() *pooledValue[int] { |