Commit 4f1ef563 authored by James Tucker's avatar James Tucker Committed by Brad Fitzpatrick

database/sql: improve standard deviation response time under high concurrency

See https://github.com/raggi/go-and-java for runtime benchmark.

The patch reduces the amount of map key search, moving connection oriented
variables onto the connection structs.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/8092045
parent b6f798f3
...@@ -193,11 +193,9 @@ type DB struct { ...@@ -193,11 +193,9 @@ type DB struct {
dsn string dsn string
mu sync.Mutex // protects following fields mu sync.Mutex // protects following fields
outConn map[*driverConn]bool // whether the conn is in use
freeConn []*driverConn freeConn []*driverConn
closed bool closed bool
dep map[finalCloser]depSet dep map[finalCloser]depSet
onConnPut map[*driverConn][]func() // code (with mu held) run when conn is next returned
lastPut map[*driverConn]string // stacktrace of last conn's put; debug only lastPut map[*driverConn]string // stacktrace of last conn's put; debug only
maxIdle int // zero means defaultMaxIdleConns; negative means 0 maxIdle int // zero means defaultMaxIdleConns; negative means 0
} }
...@@ -212,6 +210,10 @@ type driverConn struct { ...@@ -212,6 +210,10 @@ type driverConn struct {
sync.Mutex // guards following sync.Mutex // guards following
ci driver.Conn ci driver.Conn
closed bool closed bool
// guarded by db.mu
inUse bool
onPut []func() // code (with db.mu held) run when conn is next returned
} }
// the dc.db's Mutex is held. // the dc.db's Mutex is held.
...@@ -343,9 +345,7 @@ func Open(driverName, dataSourceName string) (*DB, error) { ...@@ -343,9 +345,7 @@ func Open(driverName, dataSourceName string) (*DB, error) {
db := &DB{ db := &DB{
driver: driveri, driver: driveri,
dsn: dataSourceName, dsn: dataSourceName,
outConn: make(map[*driverConn]bool),
lastPut: make(map[*driverConn]string), lastPut: make(map[*driverConn]string),
onConnPut: make(map[*driverConn][]func()),
} }
return db, nil return db, nil
} }
...@@ -427,7 +427,7 @@ func (db *DB) conn() (*driverConn, error) { ...@@ -427,7 +427,7 @@ func (db *DB) conn() (*driverConn, error) {
if n := len(db.freeConn); n > 0 { if n := len(db.freeConn); n > 0 {
conn := db.freeConn[n-1] conn := db.freeConn[n-1]
db.freeConn = db.freeConn[:n-1] db.freeConn = db.freeConn[:n-1]
db.outConn[conn] = true conn.inUse = true
db.mu.Unlock() db.mu.Unlock()
return conn, nil return conn, nil
} }
...@@ -443,7 +443,7 @@ func (db *DB) conn() (*driverConn, error) { ...@@ -443,7 +443,7 @@ func (db *DB) conn() (*driverConn, error) {
} }
db.mu.Lock() db.mu.Lock()
db.addDepLocked(dc, dc) db.addDepLocked(dc, dc)
db.outConn[dc] = true dc.inUse = true
db.mu.Unlock() db.mu.Unlock()
return dc, nil return dc, nil
} }
...@@ -456,7 +456,7 @@ func (db *DB) conn() (*driverConn, error) { ...@@ -456,7 +456,7 @@ func (db *DB) conn() (*driverConn, error) {
func (db *DB) connIfFree(wanted *driverConn) (conn *driverConn, ok bool) { func (db *DB) connIfFree(wanted *driverConn) (conn *driverConn, ok bool) {
db.mu.Lock() db.mu.Lock()
defer db.mu.Unlock() defer db.mu.Unlock()
if db.outConn[wanted] { if wanted.inUse {
return conn, false return conn, false
} }
for i, conn := range db.freeConn { for i, conn := range db.freeConn {
...@@ -465,7 +465,7 @@ func (db *DB) connIfFree(wanted *driverConn) (conn *driverConn, ok bool) { ...@@ -465,7 +465,7 @@ func (db *DB) connIfFree(wanted *driverConn) (conn *driverConn, ok bool) {
} }
db.freeConn[i] = db.freeConn[len(db.freeConn)-1] db.freeConn[i] = db.freeConn[len(db.freeConn)-1]
db.freeConn = db.freeConn[:len(db.freeConn)-1] db.freeConn = db.freeConn[:len(db.freeConn)-1]
db.outConn[wanted] = true wanted.inUse = true
return wanted, true return wanted, true
} }
return nil, false return nil, false
...@@ -480,8 +480,8 @@ var putConnHook func(*DB, *driverConn) ...@@ -480,8 +480,8 @@ var putConnHook func(*DB, *driverConn)
func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) { func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) {
db.mu.Lock() db.mu.Lock()
defer db.mu.Unlock() defer db.mu.Unlock()
if db.outConn[c] { if c.inUse {
db.onConnPut[c] = append(db.onConnPut[c], func() { c.onPut = append(c.onPut, func() {
si.Close() si.Close()
}) })
} else { } else {
...@@ -497,7 +497,7 @@ const debugGetPut = false ...@@ -497,7 +497,7 @@ const debugGetPut = false
// err is optionally the last error that occurred on this connection. // err is optionally the last error that occurred on this connection.
func (db *DB) putConn(dc *driverConn, err error) { func (db *DB) putConn(dc *driverConn, err error) {
db.mu.Lock() db.mu.Lock()
if !db.outConn[dc] { if !dc.inUse {
if debugGetPut { if debugGetPut {
fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc]) fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
} }
...@@ -506,14 +506,12 @@ func (db *DB) putConn(dc *driverConn, err error) { ...@@ -506,14 +506,12 @@ func (db *DB) putConn(dc *driverConn, err error) {
if debugGetPut { if debugGetPut {
db.lastPut[dc] = stack() db.lastPut[dc] = stack()
} }
delete(db.outConn, dc) dc.inUse = false
if fns, ok := db.onConnPut[dc]; ok { for _, fn := range dc.onPut {
for _, fn := range fns {
fn() fn()
} }
delete(db.onConnPut, dc) dc.onPut = nil
}
if err == driver.ErrBadConn { if err == driver.ErrBadConn {
// Don't reuse bad connections. // Don't reuse bad connections.
......
...@@ -7,7 +7,9 @@ package sql ...@@ -7,7 +7,9 @@ package sql
import ( import (
"fmt" "fmt"
"reflect" "reflect"
"runtime"
"strings" "strings"
"sync"
"testing" "testing"
"time" "time"
) )
...@@ -36,7 +38,14 @@ const fakeDBName = "foo" ...@@ -36,7 +38,14 @@ const fakeDBName = "foo"
var chrisBirthday = time.Unix(123456789, 0) var chrisBirthday = time.Unix(123456789, 0)
func newTestDB(t *testing.T, name string) *DB { type testOrBench interface {
Fatalf(string, ...interface{})
Errorf(string, ...interface{})
Fatal(...interface{})
Error(...interface{})
}
func newTestDB(t testOrBench, name string) *DB {
db, err := Open("test", fakeDBName) db, err := Open("test", fakeDBName)
if err != nil { if err != nil {
t.Fatalf("Open: %v", err) t.Fatalf("Open: %v", err)
...@@ -53,14 +62,14 @@ func newTestDB(t *testing.T, name string) *DB { ...@@ -53,14 +62,14 @@ func newTestDB(t *testing.T, name string) *DB {
return db return db
} }
func exec(t *testing.T, db *DB, query string, args ...interface{}) { func exec(t testOrBench, db *DB, query string, args ...interface{}) {
_, err := db.Exec(query, args...) _, err := db.Exec(query, args...)
if err != nil { if err != nil {
t.Fatalf("Exec of %q: %v", query, err) t.Fatalf("Exec of %q: %v", query, err)
} }
} }
func closeDB(t *testing.T, db *DB) { func closeDB(t testOrBench, db *DB) {
if e := recover(); e != nil { if e := recover(); e != nil {
fmt.Printf("Panic: %v\n", e) fmt.Printf("Panic: %v\n", e)
panic(e) panic(e)
...@@ -844,3 +853,63 @@ func TestCloseConnBeforeStmts(t *testing.T) { ...@@ -844,3 +853,63 @@ func TestCloseConnBeforeStmts(t *testing.T) {
t.Errorf("after Stmt Close, driverConn's Conn interface should be nil") t.Errorf("after Stmt Close, driverConn's Conn interface should be nil")
} }
} }
func manyConcurrentQueries(t testOrBench) {
maxProcs, numReqs := 16, 500
if testing.Short() {
maxProcs, numReqs = 4, 50
}
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs))
db := newTestDB(t, "people")
defer closeDB(t, db)
stmt, err := db.Prepare("SELECT|people|name|")
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
wg.Add(numReqs)
reqs := make(chan bool)
defer close(reqs)
for i := 0; i < maxProcs*2; i++ {
go func() {
for _ = range reqs {
rows, err := stmt.Query()
if err != nil {
t.Errorf("error on query: %v", err)
wg.Done()
continue
}
var name string
for rows.Next() {
rows.Scan(&name)
}
rows.Close()
wg.Done()
}
}()
}
for i := 0; i < numReqs; i++ {
reqs <- true
}
wg.Wait()
}
func TestConcurrency(t *testing.T) {
manyConcurrentQueries(t)
}
func BenchmarkConcurrency(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
manyConcurrentQueries(b)
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment