Skip to content

Commit de0ae43

Browse files
author
gbbr
committed
Pool readability proposal
1 parent fb299db commit de0ae43

2 files changed

Lines changed: 80 additions & 85 deletions

File tree

‎chapter7/patterns/pool/main/main.go‎

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,45 +15,35 @@ import (
1515
)
1616

1717
const (
18-
// maxGoroutines is the number of routines to use.
19-
maxGoroutines = 25
20-
21-
// pooledResources is the number of resources to pool.
22-
pooledResources = 2
18+
maxGoroutines = 25 // the number of routines to use.
19+
pooledResources = 2 // number of resources in the pool
2320
)
2421

2522
var (
26-
// connectionID maintains a counter.
27-
connectionID int32
28-
29-
// wg is used to wait for the program to finish.
30-
wg sync.WaitGroup
23+
connectionID int32 // counter
24+
wg sync.WaitGroup // waits for program to finish
3125
)
3226

3327
// dbConnection simulates a resource to share.
34-
type dbConnection struct {
35-
ID int32
36-
}
28+
type dbConnection struct{ ID int32 }
3729

3830
// Close implements the interface for the pool package.
3931
// Close performs any resource release management.
4032
func (dbConn *dbConnection) Close() {
4133
fmt.Println("Close: Connection", dbConn.ID)
42-
return
4334
}
4435

4536
// createConnection is a factory method called by the pool
4637
// framework when new connections are needed.
4738
func createConnection() (pool.Resource, error) {
4839
id := atomic.AddInt32(&connectionID, 1)
49-
5040
fmt.Println("Create: New Connection", id)
41+
5142
return &dbConnection{id}, nil
5243
}
5344

5445
// main is the entry point for all Go programs.
5546
func main() {
56-
// Add a count for each goroutine.
5747
wg.Add(maxGoroutines)
5848

5949
// Create the buffered channel to hold
@@ -64,8 +54,12 @@ func main() {
6454
}
6555

6656
// Perform queries using a connection from the pool.
67-
for query := 0; query < maxGoroutines; query++ {
68-
go performQueries(query, p)
57+
for q := 0; q < maxGoroutines; q++ {
58+
go func() {
59+
performQueries(q, p)
60+
wg.Done()
61+
}()
62+
6963
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
7064
}
7165

@@ -78,21 +72,18 @@ func main() {
7872
}
7973

8074
// performQueries tests the resource pool of connections.
81-
func performQueries(query int, p *pool.Pool) {
82-
// Schedule the call to Done to tell main we are done.
83-
defer wg.Done()
84-
75+
func performQueries(query int, p pool.Interface) {
8576
// Acquire a connection from the pool.
8677
conn, err := p.Acquire()
8778
if err != nil {
8879
fmt.Println(err)
8980
return
9081
}
9182

92-
// Release the connection back to the pool.
93-
defer p.Release(conn)
94-
9583
// Wait to simulate a query response.
9684
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
9785
fmt.Printf("Query: QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID)
86+
87+
// Release the connection back to the pool.
88+
p.Release(conn)
9889
}

‎chapter7/patterns/pool/pool.go‎

Lines changed: 64 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -12,102 +12,106 @@ import (
1212
"sync"
1313
)
1414

15-
type (
16-
// Resource must be implemented by types to use the pool.
17-
Resource interface {
18-
Close()
19-
}
15+
// Pool manages a set of resources that can be acquired, released and closed.
16+
// We name it Interface because when the package is imported it will be used
17+
// as pool.Interface, which is better semantics.
18+
type Interface interface {
19+
Acquire() (Resource, error)
20+
Release(Resource)
21+
Close()
22+
}
2023

21-
// Factory is a user supplied function that creates resources.
22-
Factory func() (Resource, error)
23-
)
24+
// An interface allows us to decouple the pool from its implementation, which is
25+
// a good practice for writing testable and maintainable software.
2426

25-
type (
26-
// resources is a named type for the channel of resources.
27-
queue chan Resource
28-
29-
// Pool contains a queue of resources and methods that provide
30-
// support to share resources between goroutines.
31-
Pool struct {
32-
mutex sync.Mutex
33-
resources queue
34-
factory Factory
35-
closed bool
36-
}
37-
)
27+
// Resource must be implemented by types to use the pool.
28+
type Resource interface {
29+
Close()
30+
}
31+
32+
// Pool provides a set of resources that can be shared safely by multiple goroutines
33+
type pool struct {
34+
sync.Mutex
35+
resources chan Resource
36+
factory func() (Resource, error)
37+
closed bool
38+
}
39+
40+
// ErrInvalidCapacity is returned when there has been an attempt to create an
41+
// unbuffered pool.
42+
var ErrInvalidCapacity = errors.New("Capacity needs to be greater than zero.")
3843

39-
// New creates a pool for managing resources.
40-
func New(factory Factory, capacity int) (*Pool, error) {
41-
// Check the capacity is greater than zero else
42-
// we could create an unbuffered channel or panic.
43-
if capacity <= 0 {
44-
return nil, fmt.Errorf("Invalid Capacity Value: %d", capacity)
44+
// New creates a pool from a set of factory functions. pool provides a set of
45+
// resources that can be shared safely by multiple goroutines
46+
func New(fn func() (Resource, error), capacity uint) (*pool, error) {
47+
if capacity == 0 {
48+
return nil, ErrInvalidCapacity
4549
}
4650

47-
return &Pool{
48-
factory: factory,
49-
resources: make(queue, capacity),
51+
return &pool{
52+
factory: fn,
53+
resources: make(chan Resource, capacity),
5054
}, nil
5155
}
5256

5357
// Acquire retrieves a resource from the pool.
54-
func (p *Pool) Acquire() (Resource, error) {
58+
func (p *pool) Acquire() (Resource, error) {
5559
select {
56-
case resource, ok := <-p.resources:
60+
// Check for a free resource
61+
case r, ok := <-p.resources:
5762
fmt.Println("Acquire:", "Shared Resource")
5863
if !ok {
5964
return nil, errors.New("Pool has been closed.")
6065
}
61-
return resource, nil
66+
return r, nil
6267

68+
// Or provide a new one
6369
default:
6470
fmt.Println("Acquire:", "New Resource")
6571
return p.factory()
6672
}
6773
}
6874

69-
// Release places the resource back into the queue or closes
70-
// the resource for good.
71-
func (p *Pool) Release(resource Resource) {
72-
// Secure this operation with the Close operation.
73-
p.mutex.Lock()
74-
defer p.mutex.Unlock()
75-
76-
// If the pool is closed, close the resource before returning.
75+
// Release places a new resource onto the pool
76+
func (p *pool) Release(r Resource) {
77+
// If the pool is closed, discard the resource.
7778
if p.closed {
78-
resource.Close()
79+
r.Close()
7980
return
8081
}
8182

82-
// The queue is still open so release the resource.
83+
// Secure this operation with the Close operation.
84+
p.Lock()
85+
defer p.Unlock()
8386

8487
select {
85-
// Attempt to place the resource back into the queue first. If the queue
86-
// is full, then the default case will be executed.
87-
case p.resources <- resource:
88+
// Attempt to place the new resource on the queue.
89+
case p.resources <- r:
8890
fmt.Println("Release:", "In Queue")
8991

90-
// The queue is full so just close this resource.
92+
// If the queue is already at capacity we close the resource.
9193
default:
9294
fmt.Println("Release:", "Closing")
93-
resource.Close()
95+
r.Close()
9496
}
9597
}
9698

9799
// Close will shutdown the pool and close all existing resources.
98-
func (p *Pool) Close() {
99-
// Secure this operation with the Release operation.
100-
p.mutex.Lock()
101-
defer p.mutex.Unlock()
100+
func (p *pool) Close() {
101+
if p.closed {
102+
return
103+
}
102104

103-
// If the pool is not closed, the close it down.
104-
if !p.closed {
105-
p.closed = true
105+
// Secure this operation with the Release operation.
106+
p.Lock()
107+
defer p.Unlock()
106108

107-
// Close the queue and close all existing resources.
108-
close(p.resources)
109-
for resource := range p.resources {
110-
resource.Close()
111-
}
109+
// Close the resources
110+
for r := range p.resources {
111+
r.Close()
112112
}
113+
// Close the channel
114+
close(p.resources)
115+
// Toggle the flag
116+
p.closed = true
113117
}

0 commit comments

Comments
 (0)