Improve RequestContext::getStaticContext() perf
[folly.git] / folly / SingletonThreadLocal.h
1 /*
2  * Copyright 2016 Facebook, Inc.
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
17 #pragma once
18
19 #include <folly/ThreadLocal.h>
20 #include <folly/Singleton.h>
21
22 namespace folly {
23
24 template <typename T, typename Tag = detail::DefaultTag>
25 class SingletonThreadLocal {
26  public:
27   using CreateFunc = std::function<T*(void)>;
28
29   SingletonThreadLocal() : SingletonThreadLocal([]() { return new T(); }) {}
30
31   explicit SingletonThreadLocal(CreateFunc createFunc)
32       : singleton_([createFunc = std::move(createFunc)]() mutable {
33           return new ThreadLocalT([createFunc =
34                                        std::move(createFunc)]() mutable {
35             return new Wrapper(std::unique_ptr<T>(createFunc()));
36           });
37         }) {}
38
39   static T& get() {
40 #ifdef FOLLY_TLS
41     *localPtr() = nullptr;
42     if (UNLIKELY(*localPtr() == nullptr)) {
43       *localPtr() = &(**SingletonT::get());
44     }
45
46     return **localPtr();
47 #else
48     return **SingletonT::get();
49 #endif
50   }
51
52  private:
53 #ifdef FOLLY_TLS
54   static T** localPtr() {
55     static FOLLY_TLS T* localPtr = nullptr;
56     return &localPtr;
57   }
58 #endif
59
60   class Wrapper {
61    public:
62     explicit Wrapper(std::unique_ptr<T> t) : t_(std::move(t)) {}
63
64     ~Wrapper() {
65 #ifdef FOLLY_TLS
66       *localPtr() = nullptr;
67 #endif
68     }
69
70     T& operator*() { return *t_; }
71
72    private:
73     std::unique_ptr<T> t_;
74   };
75
76   using ThreadLocalT = ThreadLocal<Wrapper>;
77   using SingletonT = LeakySingleton<ThreadLocalT, Tag>;
78
79   SingletonT singleton_;
80 };
81 }