Skip to content

Commit ef32c4f

Browse files
committed
singleflight: Add an example
I was curious about the best way to initialize a Group - it turns out you just do `var g Group` - but figured this package could use a package-level example demonstrating an example use case.
1 parent a6b377e commit ef32c4f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

singleflight/example_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Copyright 2016 Google Inc.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package singleflight_test
18+
19+
import (
20+
"fmt"
21+
"sync/atomic"
22+
"time"
23+
24+
"github.com/golang/groupcache/singleflight"
25+
)
26+
27+
var counter int32
28+
29+
func expensiveNetworkCall() (interface{}, error) {
30+
time.Sleep(1)
31+
atomic.AddInt32(&counter, 1)
32+
return counter, nil
33+
}
34+
35+
func Example() {
36+
var g singleflight.Group
37+
// No matter how many threads call Do, only one network call per key
38+
// will be in progress at any time. Callers that share a key will get the
39+
// same results.
40+
v, _ := g.Do("key", expensiveNetworkCall)
41+
fmt.Println(v.(int32))
42+
// Output: 1
43+
}

0 commit comments

Comments
 (0)