| 1 | # concurrent map [](https://travis-ci.com/orcaman/concurrent-map) |
| 2 | |
| 3 | As explained [here](http://golang.org/doc/faq#atomic_maps) and [here](http://blog.golang.org/go-maps-in-action), the `map` type in Go doesn't support concurrent reads and writes. `concurrent-map` provides a high-performance solution to this by sharding the map with minimal time spent waiting for locks. |
| 4 | |
| 5 | Prior to Go 1.9, there was no concurrent map implementation in the stdlib. In Go 1.9, `sync.Map` was introduced. The new `sync.Map` has a few key differences from this map. The stdlib `sync.Map` is designed for append-only scenarios. So if you want to use the map for something more like in-memory db, you might benefit from using our version. You can read more about it in the golang repo, for example [here](https://github.com/golang/go/issues/21035) and [here](https://stackoverflow.com/questions/11063473/map-with-concurrent-access) |
| 6 | |
| 7 | ## usage |
| 8 | |
| 9 | Import the package: |
| 10 | |
| 11 | ```go |
| 12 | import ( |
| 13 | "github.com/orcaman/concurrent-map/v2" |
| 14 | ) |
| 15 | |
| 16 | ``` |
| 17 | |
| 18 | ```bash |
| 19 | go get "github.com/orcaman/concurrent-map/v2" |
| 20 | ``` |
| 21 | |
| 22 | The package is now imported under the "cmap" namespace. |
| 23 | |
| 24 | ## example |
| 25 | |
| 26 | ```go |
| 27 | |
| 28 | // Create a new map. |
| 29 | m := cmap.New[string]() |
| 30 | |
| 31 | // Sets item within map, sets "bar" under key "foo" |
| 32 | m.Set("foo", "bar") |
| 33 | |
| 34 | // Retrieve item from map. |
| 35 | bar, ok := m.Get("foo") |
| 36 | |
| 37 | // Removes item under key "foo" |
| 38 | m.Remove("foo") |
| 39 | |
| 40 | ``` |
| 41 | |
| 42 | For more examples have a look at concurrent_map_test.go. |
| 43 | |
| 44 | Running tests: |
| 45 | |
| 46 | ```bash |
| 47 | go test "github.com/orcaman/concurrent-map/v2" |
| 48 | ``` |
| 49 | |
| 50 | ## guidelines for contributing |
| 51 | |
| 52 | Contributions are highly welcome. In order for a contribution to be merged, please follow these guidelines: |
| 53 | - Open an issue and describe what you are after (fixing a bug, adding an enhancement, etc.). |
| 54 | - According to the core team's feedback on the above mentioned issue, submit a pull request, describing the changes and linking to the issue. |
| 55 | - New code must have test coverage. |
| 56 | - If the code is about performance issues, you must include benchmarks in the process (either in the issue or in the PR). |
| 57 | - In general, we would like to keep `concurrent-map` as simple as possible and as similar to the native `map`. Please keep this in mind when opening issues. |
| 58 | |
| 59 | ## language |
| 60 | - [中文说明](./README-zh.md) |
| 61 | |
| 62 | ## license |
| 63 | MIT (see [LICENSE](https://github.com/orcaman/concurrent-map/blob/master/LICENSE) file) |