From 460900544c95c98bbf6b841619aed9b9bdd381fc Mon Sep 17 00:00:00 2001 From: phuslu Date: Sat, 26 Oct 2024 13:02:13 +0800 Subject: [PATCH] Revert "forbidden magic (sync.Pool + runtime.SetFinalizer)" This reverts commit cebd120a9773a64d834a8e8adf00e692ba972ce7. --- client_dialer.go | 27 +++++++++++++-------------- client_test.go | 14 +++++++------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/client_dialer.go b/client_dialer.go index b82ed21..1def933 100644 --- a/client_dialer.go +++ b/client_dialer.go @@ -8,7 +8,6 @@ import ( "net/http" "net/url" "reflect" - "runtime" "sync" "time" "unsafe" @@ -31,7 +30,7 @@ type UDPDialer struct { MaxConns uint16 once sync.Once - conns sync.Pool + conns []*udpConn } func (d *UDPDialer) DialContext(ctx context.Context, network, addr string) (conn net.Conn, err error) { @@ -43,16 +42,18 @@ func (d *UDPDialer) get() (net.Conn, error) { if d.MaxConns == 0 { d.MaxConns = 64 } - d.conns = sync.Pool{ - New: func() any { - conn, _ := net.DialUDP("udp", nil, d.Addr) - runtime.SetFinalizer(conn, udpConnFinalizer) - return conn - }, + d.conns = make([]*udpConn, d.MaxConns) + for i := range d.MaxConns { + d.conns[i] = new(udpConn) + d.conns[i].UDPConn, _ = net.DialUDP("udp", nil, d.Addr) } }) - c := d.conns.Get().(net.Conn) + c := d.conns[cheaprandn(uint32(d.MaxConns))] + if !c.mu.TryLock() { + c = d.conns[cheaprandn(uint32(d.MaxConns))] + c.mu.Lock() + } if d.Timeout > 0 { _ = c.SetDeadline(time.Now().Add(d.Timeout)) @@ -61,12 +62,10 @@ func (d *UDPDialer) get() (net.Conn, error) { return c, nil } -func udpConnFinalizer(conn net.Conn) { - _ = conn.Close() -} - func (d *UDPDialer) put(conn net.Conn) { - d.conns.Put(conn) + if c, _ := conn.(*udpConn); c != nil { + c.mu.Unlock() + } } type udpConn struct { diff --git a/client_test.go b/client_test.go index 1c4a622..c5a31f2 100644 --- a/client_test.go +++ b/client_test.go @@ -89,13 +89,13 @@ func TestClientLookup(t *testing.T) { MaxConns: 1000, }, }, - // { - // Addr: "https://1.1.1.1/dns-query", - // Dialer: &HTTPDialer{ - // Endpoint: func() (u *url.URL) { u, _ = url.Parse("https://1.1.1.1/dns-query"); return }(), - // UserAgent: "fastdns/0.9", - // }, - // }, + { + Addr: "https://1.1.1.1/dns-query", + Dialer: &HTTPDialer{ + Endpoint: func() (u *url.URL) { u, _ = url.Parse("https://1.1.1.1/dns-query"); return }(), + UserAgent: "fastdns/0.9", + }, + }, } deref := func(value any) any {