Skip to content

Commit

Permalink
Revert "forbidden magic (sync.Pool + runtime.SetFinalizer)"
Browse files Browse the repository at this point in the history
This reverts commit cebd120.
  • Loading branch information
phuslu committed Oct 26, 2024
1 parent cebd120 commit 4609005
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 21 deletions.
27 changes: 13 additions & 14 deletions client_dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"net/http"
"net/url"
"reflect"
"runtime"
"sync"
"time"
"unsafe"
Expand All @@ -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) {
Expand All @@ -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))
Expand All @@ -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 {
Expand Down
14 changes: 7 additions & 7 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 4609005

Please sign in to comment.