Skip to content

Commit

Permalink
forbidden magic (sync.Pool + runtime.SetFinalizer)
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Oct 26, 2024
1 parent 036d2f9 commit cebd120
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 20 deletions.
27 changes: 14 additions & 13 deletions client_dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"net/url"
"reflect"
"runtime"
"sync"
"time"
"unsafe"
Expand All @@ -30,7 +31,7 @@ type UDPDialer struct {
MaxConns uint16

once sync.Once
conns []*udpConn
conns sync.Pool
}

func (d *UDPDialer) DialContext(ctx context.Context, network, addr string) (conn net.Conn, err error) {
Expand All @@ -42,18 +43,16 @@ func (d *UDPDialer) get() (net.Conn, error) {
if d.MaxConns == 0 {
d.MaxConns = 64
}
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)
d.conns = sync.Pool{
New: func() any {
conn, _ := net.DialUDP("udp", nil, d.Addr)
runtime.SetFinalizer(conn, udpConnFinalizer)
return conn
},
}
})

c := d.conns[cheaprandn(uint32(d.MaxConns))]
if !c.mu.TryLock() {
c = d.conns[cheaprandn(uint32(d.MaxConns))]
c.mu.Lock()
}
c := d.conns.Get().(net.Conn)

if d.Timeout > 0 {
_ = c.SetDeadline(time.Now().Add(d.Timeout))
Expand All @@ -62,10 +61,12 @@ func (d *UDPDialer) get() (net.Conn, error) {
return c, nil
}

func udpConnFinalizer(conn net.Conn) {
_ = conn.Close()
}

func (d *UDPDialer) put(conn net.Conn) {
if c, _ := conn.(*udpConn); c != nil {
c.mu.Unlock()
}
d.conns.Put(conn)
}

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 cebd120

Please sign in to comment.