OSDN Git Service

Merge branch 'dev' into dev-verify
[bytom/bytom.git] / sync / idempotency / group.go
1 /*
2 Copyright 2012 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 idempotency provides a duplicate function call suppression
18 // mechanism. It is a lightly modified version of groupcache's
19 // singleflight package that does not forget keys until explicitly
20 // told to.
21 package idempotency
22
23 import "sync"
24
25 // call is an in-flight or completed Once call
26 type call struct {
27         wg  sync.WaitGroup
28         val interface{}
29         err error
30 }
31
32 // Group represents a class of work and forms a namespace in which
33 // units of work can be executed with duplicate suppression.
34 type Group struct {
35         mu sync.Mutex       // protects m
36         m  map[string]*call // lazily initialized
37 }
38
39 // Once executes and returns the results of the given function, making
40 // sure that only one execution for a given key happens until the
41 // key is explicitly forgotten. If a duplicate comes in, the duplicate
42 // caller waits for the original to complete and receives the same results.
43 func (g *Group) Once(key string, fn func() (interface{}, error)) (interface{}, error) {
44         g.mu.Lock()
45         if g.m == nil {
46                 g.m = make(map[string]*call)
47         }
48         if c, ok := g.m[key]; ok {
49                 g.mu.Unlock()
50                 c.wg.Wait()
51                 return c.val, c.err
52         }
53         c := new(call)
54         c.wg.Add(1)
55         g.m[key] = c
56         g.mu.Unlock()
57
58         c.val, c.err = fn()
59         if c.err != nil {
60                 g.mu.Lock()
61                 delete(g.m, key)
62                 g.mu.Unlock()
63         }
64         c.wg.Done()
65
66         return c.val, c.err
67 }
68
69 // Forget forgets a key, allowing the next call for the key to execute
70 // the function.
71 func (g *Group) Forget(key string) {
72         g.mu.Lock()
73         delete(g.m, key)
74         g.mu.Unlock()
75 }