ConcurrentMap.h revision 84888d3553c7595ee57dc73023ae94a27895de0d
1/*
2 * Copyright (C) 2016 The Android Open Source Project
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#ifndef ANDROID_HIDL_CONCURRENT_MAP_H
17#define ANDROID_HIDL_CONCURRENT_MAP_H
18
19#include <mutex>
20#include <map>
21
22namespace android {
23namespace hardware {
24
25template<typename K, typename V>
26class ConcurrentMap {
27private:
28    using size_type = typename std::map<K, V>::size_type;
29    using iterator = typename std::map<K, V>::iterator;
30    using const_iterator = typename std::map<K, V>::const_iterator;
31
32public:
33    void set(K &&k, V &&v) {
34        std::unique_lock<std::mutex> _lock(mMutex);
35        mMap[std::forward<K>(k)] = std::forward<V>(v);
36    }
37
38    // get with the given default value.
39    const V &get(const K &k, const V &def) const {
40        std::unique_lock<std::mutex> _lock(mMutex);
41        const_iterator iter = mMap.find(k);
42        if (iter == mMap.end()) {
43            return def;
44        }
45        return iter->second;
46    }
47
48    size_type erase(const K &k) {
49        std::unique_lock<std::mutex> _lock(mMutex);
50        return mMap.erase(k);
51    }
52
53private:
54    mutable std::mutex mMutex;
55    std::map<K, V> mMap;
56};
57
58}  // namespace hardware
59}  // namespace android
60
61
62#endif  // ANDROID_HIDL_CONCURRENT_MAP_H
63