/*
- * Copyright 2015 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
#include <map>
#include <memory>
#include <glog/logging.h>
-#include <folly/ThreadLocal.h>
#include <folly/RWSpinLock.h>
+#include <folly/SingletonThreadLocal.h>
namespace folly {
class RequestData {
public:
- virtual ~RequestData() {}
+ virtual ~RequestData() = default;
};
class RequestContext;
}
}
+ // Unlike setContextData, this method does not panic if the key is already
+ // present. Returns true iff the new value has been inserted.
+ bool setContextDataIfAbsent(const std::string& val,
+ std::unique_ptr<RequestData> data) {
+ folly::RWSpinLock::UpgradedHolder guard(lock);
+ if (data_.find(val) != data_.end()) {
+ return false;
+ }
+
+ folly::RWSpinLock::WriteHolder writeGuard(std::move(guard));
+ data_[val] = std::move(data);
+ return true;
+ }
+
bool hasContextData(const std::string& val) {
folly::RWSpinLock::ReadHolder guard(lock);
return data_.find(val) != data_.end();
}
private:
- // Used to solve static destruction ordering issue. Any static object
- // that uses RequestContext must call this function in its constructor.
- //
- // See below link for more details.
- // http://stackoverflow.com/questions/335369/
- // finding-c-static-initialization-order-problems#335746
- static std::shared_ptr<RequestContext> &getStaticContext() {
- static folly::ThreadLocal<std::shared_ptr<RequestContext> > context;
- return *context;
- }
+ static std::shared_ptr<RequestContext>& getStaticContext();
folly::RWSpinLock lock;
std::map<std::string, std::unique_ptr<RequestData>> data_;