Fabric: ContextContainer::findInstance returns an optional intead of throwing an exception

Summary: Sometimes we don't know for sure if `ContextContainer` has a value or not (and that's perfectly legit use case). In those cases now we can use `findInstance` method that returns an optional intead of throwing an exeption.

Reviewed By: JoshuaGross

Differential Revision: D15039137

fbshipit-source-id: 95ba8cc7b76e37d1bd17e18c0098e56350ff3fef
This commit is contained in:
Valentin Shergin
2019-04-29 21:17:39 -07:00
committed by Facebook Github Bot
parent 6d9f0a7d2a
commit 718ffe5038

View File

@@ -51,6 +51,7 @@ class ContextContainer final {
/*
* Returns a previously registered instance of the particular type `T`
* for `key`.
* Throws an exception if the instance could not be found.
*/
template <typename T>
T getInstance(std::string const &key) const {
@@ -65,6 +66,27 @@ class ContextContainer final {
return *std::static_pointer_cast<T>(instances_.at(key));
}
/*
* Returns a (wrapped in an optional) previously registered instance of
* the particular type `T` for given `key`.
* Returns an empty optional if the instance could not be found.
*/
template <typename T>
better::optional<T> findInstance(std::string const &key) const {
std::shared_lock<better::shared_mutex> lock(mutex_);
auto iterator = instances_.find(key);
if (iterator == instances_.end()) {
return {};
}
assert(
typeHashes_.at(key) == typeid(T).hash_code() &&
"ContextContainer stores an instance of different type for given key.");
return *std::static_pointer_cast<T>(iterator->second);
}
private:
mutable better::shared_mutex mutex_;
// Protected by mutex_`.