| 1 | package gcache |
| 2 | |
| 3 | /* |
| 4 | Copyright 2012 Google Inc. |
| 5 | |
| 6 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | you may not use this file except in compliance with the License. |
| 8 | You may obtain a copy of the License at |
| 9 | |
| 10 | http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | |
| 12 | Unless required by applicable law or agreed to in writing, software |
| 13 | distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | See the License for the specific language governing permissions and |
| 16 | limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | // This module provides a duplicate function call suppression |
| 20 | // mechanism. |
| 21 | |
| 22 | import "sync" |
| 23 | |
| 24 | // call is an in-flight or completed Do call |
| 25 | type call struct { |
| 26 | wg sync.WaitGroup |
| 27 | val interface{} |
| 28 | err error |
| 29 | } |
| 30 | |
| 31 | // Group represents a class of work and forms a namespace in which |
| 32 | // units of work can be executed with duplicate suppression. |
| 33 | type Group struct { |
| 34 | cache Cache |
| 35 | mu sync.Mutex // protects m |
| 36 | m map[interface{}]*call // lazily initialized |
| 37 | } |
| 38 | |
| 39 | // Do executes and returns the results of the given function, making |
| 40 | // sure that only one execution is in-flight for a given key at a |
| 41 | // time. If a duplicate comes in, the duplicate caller waits for the |
| 42 | // original to complete and receives the same results. |
| 43 | func (g *Group) Do(key interface{}, fn func() (interface{}, error), isWait bool) (interface{}, bool, error) { |
| 44 | g.mu.Lock() |
| 45 | v, err := g.cache.get(key, true) |
| 46 | if err == nil { |
| 47 | g.mu.Unlock() |
| 48 | return v, false, nil |
| 49 | } |
| 50 | if g.m == nil { |
| 51 | g.m = make(map[interface{}]*call) |
| 52 | } |
| 53 | if c, ok := g.m[key]; ok { |
| 54 | g.mu.Unlock() |
| 55 | if !isWait { |
| 56 | return nil, false, KeyNotFoundError |
| 57 | } |
| 58 | c.wg.Wait() |
| 59 | return c.val, false, c.err |
| 60 | } |
| 61 | c := new(call) |
| 62 | c.wg.Add(1) |
| 63 | g.m[key] = c |
| 64 | g.mu.Unlock() |
| 65 | if !isWait { |
| 66 | go g.call(c, key, fn) |
| 67 | return nil, false, KeyNotFoundError |
| 68 | } |
| 69 | v, err = g.call(c, key, fn) |
| 70 | return v, true, err |
| 71 | } |
| 72 | |
| 73 | func (g *Group) call(c *call, key interface{}, fn func() (interface{}, error)) (interface{}, error) { |
| 74 | c.val, c.err = fn() |
| 75 | c.wg.Done() |
| 76 | |
| 77 | g.mu.Lock() |
| 78 | delete(g.m, key) |
| 79 | g.mu.Unlock() |
| 80 | |
| 81 | return c.val, c.err |
| 82 | } |