Skip to content

Commit

Permalink
singleflight: Add an example
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kevinburke committed Oct 28, 2016
1 parent a6b377e commit 8340aba
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions singleflight/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package singleflight_test

import (
"fmt"
"log"
"sync/atomic"
"time"

"github.com/golang/groupcache/singleflight"
)

var counter int32
var networkGroup singleflight.Group

// expensiveNetworkCall simulates an expensive action.
func expensiveNetworkCall() (interface{}, error) {
time.Sleep(1)
atomic.AddInt32(&counter, 1)
return counter, nil
}

func Example() {
// No matter how many threads call Do, only one network call per key will
// be in progress at any time. Callers that share a key will get the same
// results as an in-flight call with that key.
v, err := networkGroup.Do("key", expensiveNetworkCall)
if err != nil {
log.Fatal(err)
}
fmt.Println(v.(int32))
// Output: 1
}

0 comments on commit 8340aba

Please sign in to comment.