Skip to content

Commit f3f9685

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 f3f9685

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

singleflight/example_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
var g singleflight.Group
29+
30+
// expensiveNetworkCall simulates an expensive action.
31+
func expensiveNetworkCall() (interface{}, error) {
32+
time.Sleep(1)
33+
atomic.AddInt32(&counter, 1)
34+
return counter, nil
35+
}
36+
37+
func Example() {
38+
// No matter how many threads call Do, only one network call per key will
39+
// be in progress at any time. Callers that share a key will get the same
40+
// results as an in-flight call with that key.
41+
v, _ := g.Do("key", expensiveNetworkCall)
42+
fmt.Println(v.(int32))
43+
// Output: 1
44+
}

0 commit comments

Comments
 (0)