fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[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     if (UNLIKELY(*localPtr() == nullptr)) {
42       *localPtr() = &(**SingletonT::get());
43     }
44
45     return **localPtr();
46 #else
47     return **SingletonT::get();
48 #endif
49   }
50
51  private:
52 #ifdef FOLLY_TLS
53   static T** localPtr() {
54     static FOLLY_TLS T* localPtr = nullptr;
55     return &localPtr;
56   }
57 #endif
58
59   class Wrapper {
60    public:
61     explicit Wrapper(std::unique_ptr<T> t) : t_(std::move(t)) {}
62
63     ~Wrapper() {
64 #ifdef FOLLY_TLS
65       *localPtr() = nullptr;
66 #endif
67     }
68
69     T& operator*() { return *t_; }
70
71    private:
72     std::unique_ptr<T> t_;
73   };
74
75   using ThreadLocalT = ThreadLocal<Wrapper>;
76   using SingletonT = LeakySingleton<ThreadLocalT, Tag>;
77
78   SingletonT singleton_;
79 };
80 }