|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. 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 | + */ |
| 17 | + |
| 18 | +#ifndef JNI_ID_TO_MODULE_MAP_H |
| 19 | +#define JNI_ID_TO_MODULE_MAP_H |
| 20 | + |
| 21 | +#include <memory> |
| 22 | +#include <mutex> |
| 23 | +#include <unordered_map> |
| 24 | +#include <utility> |
| 25 | + |
| 26 | +#include "arrow/util/macros.h" |
| 27 | + |
| 28 | +namespace arrow { |
| 29 | +namespace jni { |
| 30 | + |
| 31 | +/** |
| 32 | + * An utility class that map module id to module pointers. |
| 33 | + * @tparam Holder class of the object to hold. |
| 34 | + */ |
| 35 | +template <typename Holder> |
| 36 | +class ConcurrentMap { |
| 37 | + public: |
| 38 | + ConcurrentMap() : module_id_(init_module_id_) {} |
| 39 | + |
| 40 | + jlong Insert(Holder holder) { |
| 41 | + std::lock_guard<std::mutex> lock(mtx_); |
| 42 | + jlong result = module_id_++; |
| 43 | + map_.insert(std::pair<jlong, Holder>(result, holder)); |
| 44 | + return result; |
| 45 | + } |
| 46 | + |
| 47 | + void Erase(jlong module_id) { |
| 48 | + std::lock_guard<std::mutex> lock(mtx_); |
| 49 | + map_.erase(module_id); |
| 50 | + } |
| 51 | + |
| 52 | + Holder Lookup(jlong module_id) { |
| 53 | + std::lock_guard<std::mutex> lock(mtx_); |
| 54 | + auto it = map_.find(module_id); |
| 55 | + if (it != map_.end()) { |
| 56 | + return it->second; |
| 57 | + } |
| 58 | + return NULLPTR; |
| 59 | + } |
| 60 | + |
| 61 | + void Clear() { |
| 62 | + std::lock_guard<std::mutex> lock(mtx_); |
| 63 | + map_.clear(); |
| 64 | + } |
| 65 | + |
| 66 | + private: |
| 67 | + // Initialize the module id starting value to a number greater than zero |
| 68 | + // to allow for easier debugging of uninitialized java variables. |
| 69 | + static constexpr int init_module_id_ = 4; |
| 70 | + |
| 71 | + int64_t module_id_; |
| 72 | + std::mutex mtx_; |
| 73 | + // map from module ids returned to Java and module pointers |
| 74 | + std::unordered_map<jlong, Holder> map_; |
| 75 | +}; |
| 76 | + |
| 77 | +} // namespace jni |
| 78 | +} // namespace arrow |
| 79 | + |
| 80 | +#endif // JNI_ID_TO_MODULE_MAP_H |
0 commit comments