Skip to content

Commit f5409a4

Browse files
Fixed code based on community suggestions.
1 parent cbb4467 commit f5409a4

4 files changed

Lines changed: 64 additions & 63 deletions

File tree

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package main
88

99
import (
1010
"fmt"
11+
"io"
1112
"math/rand"
1213
"sync"
1314
"sync/atomic"
@@ -28,8 +29,9 @@ type dbConnection struct {
2829

2930
// Close implements the interface for the pool package.
3031
// Close performs any resource release management.
31-
func (dbConn *dbConnection) Close() {
32+
func (dbConn *dbConnection) Close() error {
3233
fmt.Println("Close: Connection", dbConn.ID)
34+
return nil
3335
}
3436

3537
// isCounter provides support for giving each
@@ -38,7 +40,7 @@ var idCounter int32
3840

3941
// createConnection is a factory method called by the pool
4042
// framework when new connections are needed.
41-
func createConnection() (pool.Resource, error) {
43+
func createConnection() (io.Closer, error) {
4244
id := atomic.AddInt32(&idCounter, 1)
4345
fmt.Println("Create: New Connection", id)
4446

@@ -79,7 +81,7 @@ func main() {
7981
}
8082

8183
// performQueries tests the resource pool of connections.
82-
func performQueries(query int, p pool.AcquireReleaseCloser) {
84+
func performQueries(query int, p *pool.Pool) {
8385
// Acquire a connection from the pool.
8486
conn, err := p.Acquire()
8587
if err != nil {

‎chapter7/patterns/pool/pool.go‎

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,15 @@ package pool
99
import (
1010
"errors"
1111
"fmt"
12+
"io"
1213
"sync"
1314
)
1415

15-
// AcquireReleaseCloser is behavior that need to be implemented
16-
// to use the pool package.
17-
type AcquireReleaseCloser interface {
18-
Acquire() (Resource, error)
19-
Release(Resource)
20-
Close()
21-
}
22-
23-
// An interface allows us to decouple the pool from its implementation, which is
24-
// a good practice for writing testable and maintainable software.
25-
26-
// Resource must be implemented by types to use the pool.
27-
type Resource interface {
28-
Close()
29-
}
30-
3116
// Pool manages a set of resources that can be shared safely by multiple goroutines.
32-
type pool struct {
17+
type Pool struct {
3318
sync.Mutex
34-
resources chan Resource
35-
factory func() (Resource, error)
19+
resources chan io.Closer
20+
factory func() (io.Closer, error)
3621
closed bool
3722
}
3823

@@ -42,19 +27,19 @@ var ErrInvalidCapacity = errors.New("Capacity needs to be greater than zero.")
4227

4328
// New creates a pool from a set of factory functions. A pool provides capacity
4429
// number of resources that can be shared safely by multiple goroutines.
45-
func New(fn func() (Resource, error), capacity uint) (AcquireReleaseCloser, error) {
30+
func New(fn func() (io.Closer, error), capacity uint) (*Pool, error) {
4631
if capacity == 0 {
4732
return nil, ErrInvalidCapacity
4833
}
4934

50-
return &pool{
35+
return &Pool{
5136
factory: fn,
52-
resources: make(chan Resource, capacity),
37+
resources: make(chan io.Closer, capacity),
5338
}, nil
5439
}
5540

5641
// Acquire retrieves a resource from the pool.
57-
func (p *pool) Acquire() (Resource, error) {
42+
func (p *Pool) Acquire() (io.Closer, error) {
5843
select {
5944
// Check for a free resource.
6045
case r, ok := <-p.resources:
@@ -72,7 +57,7 @@ func (p *pool) Acquire() (Resource, error) {
7257
}
7358

7459
// Release places a new resource onto the pool.
75-
func (p *pool) Release(r Resource) {
60+
func (p *Pool) Release(r io.Closer) {
7661
// Secure this operation with the Close operation.
7762
p.Lock()
7863
defer p.Unlock()
@@ -96,7 +81,7 @@ func (p *pool) Release(r Resource) {
9681
}
9782

9883
// Close will shutdown the pool and close all existing resources.
99-
func (p *pool) Close() {
84+
func (p *Pool) Close() {
10085
// Secure this operation with the Release operation.
10186
p.Lock()
10287
defer p.Unlock()
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright Information.
2+
3+
// This example is provided with help by Gabriel Aszalos.
4+
5+
// This sample program demonstrates how to use a channel to
6+
// monitor the amount of time the program is running and terminate
7+
// the program if it runs too long.
8+
package main
9+
10+
import (
11+
"flag"
12+
"log"
13+
"time"
14+
15+
"github.com/goinaction/code/chapter7/patterns/runner"
16+
)
17+
18+
// flagSec is a command line flag to set the timeout in seconds.
19+
var flagSec = flag.Int("ttl", 3, "timeout in seconds")
20+
21+
// main is the entry point for the program.
22+
func main() {
23+
// Parse all command line flags.
24+
flag.Parse()
25+
log.Println("Starting work.")
26+
27+
// Create a new timer value for this run.
28+
r := runner.New(time.Duration(*flagSec))
29+
30+
// Add the tasks to be run and start running.
31+
r.Add(createTask(1), createTask(2), createTask(1))
32+
r.Start()
33+
34+
log.Println("Process Ended")
35+
}
36+
37+
// createTask returns an example task that sleeps for the given
38+
// duration (in seconds).
39+
func createTask(d time.Duration) func(int) {
40+
return func(id int) {
41+
log.Printf("Processor - Task #%d", id)
42+
time.Sleep(d * time.Second)
43+
}
44+
}
Lines changed: 5 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,18 @@
22

33
// This example is provided with help by Gabriel Aszalos.
44

5-
// This sample program demonstrates how to use a channel to
6-
// monitor the amount of time the program is running and terminate
7-
// the program if it runs too long.
8-
package main
5+
// Package runner manages the running and lifetime of
6+
// the process.
7+
package runner
98

109
import (
1110
"errors"
12-
"flag"
1311
"log"
1412
"os"
1513
"os/signal"
1614
"time"
1715
)
1816

19-
// flagSec is a command line flag to set the timeout in seconds.
20-
var flagSec = flag.Int("ttl", 3, "timeout in seconds")
21-
2217
// runner runs a set of tasks on a given timeout and shuts down on os.Interrupt.
2318
type runner struct {
2419
// interrupt channel will be used to signal the runner to shut down.
@@ -34,8 +29,8 @@ type runner struct {
3429
tasks []func(int)
3530
}
3631

37-
// NewRunner returns a new ready-to-use runner.
38-
func NewRunner(d time.Duration) *runner {
32+
// New returns a new ready-to-use runner.
33+
func New(d time.Duration) *runner {
3934
return &runner{
4035
interrupt: make(chan os.Signal, 1),
4136
complete: make(chan error),
@@ -106,28 +101,3 @@ func (r *runner) gotInterrupt() bool {
106101
return false
107102
}
108103
}
109-
110-
// main is the entry point for the program.
111-
func main() {
112-
// Parse all command line flags.
113-
flag.Parse()
114-
log.Println("Starting work.")
115-
116-
// Create a new timer value for this run.
117-
r := NewRunner(time.Duration(*flagSec))
118-
119-
// Add the tasks to be run and start running.
120-
r.Add(sleeper(1), sleeper(2), sleeper(1))
121-
r.Start()
122-
123-
log.Println("Process Ended")
124-
}
125-
126-
// sleeper returns an example task that sleeps for the given
127-
// duration (in seconds).
128-
func sleeper(d time.Duration) func(int) {
129-
return func(id int) {
130-
log.Printf("Processor - Task #%d", id)
131-
time.Sleep(d * time.Second)
132-
}
133-
}

0 commit comments

Comments
 (0)