v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
lazy-instance.h
Go to the documentation of this file.
1// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_BASE_LAZY_INSTANCE_H_
6#define V8_BASE_LAZY_INSTANCE_H_
7
8// The LazyInstance<Type, Traits> class manages a single instance of Type,
9// which will be lazily created on the first time it's accessed. This class is
10// useful for places you would normally use a function-level static, but you
11// need to have guaranteed thread-safety. The Type constructor will only ever
12// be called once, even if two threads are racing to create the object. Get()
13// and Pointer() will always return the same, completely initialized instance.
14//
15// LazyInstance is completely thread safe, assuming that you create it safely.
16// The class was designed to be POD initialized, so it shouldn't require a
17// static constructor. It really only makes sense to declare a LazyInstance as
18// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
19//
20// LazyInstance is similar to Singleton, except it does not have the singleton
21// property. You can have multiple LazyInstance's of the same type, and each
22// will manage a unique instance. It also preallocates the space for Type, as
23// to avoid allocating the Type instance on the heap. This may help with the
24// performance of creating the instance, and reducing heap fragmentation. This
25// requires that Type be a complete type so we can determine the size. See
26// notes for advanced users below for more explanations.
27//
28// Example usage:
29// static LazyInstance<MyClass>::type my_instance = LAZY_INSTANCE_INITIALIZER;
30// void SomeMethod() {
31// my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
32//
33// MyClass* ptr = my_instance.Pointer();
34// ptr->DoDoDo(); // MyClass::DoDoDo
35// }
36//
37// Additionally you can override the way your instance is constructed by
38// providing your own trait:
39// Example usage:
40// struct MyCreateTrait {
41// static void Construct(void* allocated_ptr) {
42// new (allocated_ptr) MyClass(/* extra parameters... */);
43// }
44// };
45// static LazyInstance<MyClass, MyCreateTrait>::type my_instance =
46// LAZY_INSTANCE_INITIALIZER;
47//
48// WARNINGS:
49// - This implementation of LazyInstance IS THREAD-SAFE by default. See
50// SingleThreadInitOnceTrait if you don't care about thread safety.
51// - Lazy initialization comes with a cost. Make sure that you don't use it on
52// critical path. Consider adding your initialization code to a function
53// which is explicitly called once.
54//
55// Notes for advanced users:
56// LazyInstance can actually be used in two different ways:
57//
58// - "Static mode" which is the default mode since it is the most efficient
59// (no extra heap allocation). In this mode, the instance is statically
60// allocated (stored in the global data section at compile time).
61// The macro LAZY_STATIC_INSTANCE_INITIALIZER (= LAZY_INSTANCE_INITIALIZER)
62// must be used to initialize static lazy instances.
63//
64// - "Dynamic mode". In this mode, the instance is dynamically allocated and
65// constructed (using new) by default. This mode is useful if you have to
66// deal with some code already allocating the instance for you (e.g.
67// OS::Mutex() which returns a new private OS-dependent subclass of Mutex).
68// The macro LAZY_DYNAMIC_INSTANCE_INITIALIZER must be used to initialize
69// dynamic lazy instances.
70
71#include <type_traits>
72
73#include "src/base/macros.h"
74#include "src/base/once.h"
75
76namespace v8 {
77namespace base {
78
79#define LAZY_STATIC_INSTANCE_INITIALIZER { V8_ONCE_INIT, { {} } }
80#define LAZY_DYNAMIC_INSTANCE_INITIALIZER { V8_ONCE_INIT, 0 }
81
82// Default to static mode.
83#define LAZY_INSTANCE_INITIALIZER LAZY_STATIC_INSTANCE_INITIALIZER
84
85
86template <typename T>
88 static void Destroy(T* /* instance */) {}
89};
90
91
92// Traits that define how an instance is allocated and accessed.
93
94
95template <typename T>
97 using StorageType = char[sizeof(T)];
99
100 static T* MutableInstance(StorageType* storage) {
101 return reinterpret_cast<T*>(storage);
102 }
103
104 template <typename ConstructTrait>
105 static void InitStorageUsingTrait(StorageType* storage) {
106 ConstructTrait::Construct(storage);
107 }
108};
109
110
111template <typename T>
113 using StorageType = T*;
114 using AlignmentType = T*;
115
116 static T* MutableInstance(StorageType* storage) {
117 return *storage;
118 }
119
120 template <typename CreateTrait>
121 static void InitStorageUsingTrait(StorageType* storage) {
122 *storage = CreateTrait::Create();
123 }
124};
125
126
127template <typename T>
129 // Constructs the provided object which was already allocated.
130 static void Construct(void* allocated_ptr) { new (allocated_ptr) T(); }
131};
132
133
134template <typename T>
136 static T* Create() {
137 return new T();
138 }
139};
140
141
143 template <typename Function, typename Storage>
144 static void Init(OnceType* once, Function function, Storage storage) {
145 CallOnce(once, function, storage);
146 }
147};
148
149
150// Initialization trait for users who don't care about thread-safety.
152 template <typename Function, typename Storage>
153 static void Init(OnceType* once, Function function, Storage storage) {
154 if (*once == ONCE_STATE_UNINITIALIZED) {
155 function(storage);
156 *once = ONCE_STATE_DONE;
157 }
158 }
159};
160
161
162// TODO(pliard): Handle instances destruction (using global destructors).
163template <typename T, typename AllocationTrait, typename CreateTrait,
164 typename InitOnceTrait, typename DestroyTrait /* not used yet. */>
166 public:
167 using StorageType = typename AllocationTrait::StorageType;
168 using AlignmentType = typename AllocationTrait::AlignmentType;
169
170 private:
171 static void InitInstance(void* storage) {
172 AllocationTrait::template InitStorageUsingTrait<CreateTrait>(
173 static_cast<StorageType*>(storage));
174 }
175
176 void Init() const {
177 InitOnceTrait::Init(&once_, &InitInstance, static_cast<void*>(&storage_));
178 }
179
180 public:
181 T* Pointer() {
182 Init();
183 return AllocationTrait::MutableInstance(&storage_);
184 }
185
186 const T& Get() const {
187 Init();
188 return *AllocationTrait::MutableInstance(&storage_);
189 }
190
193};
194
195
196template <typename T,
197 typename CreateTrait = DefaultConstructTrait<T>,
198 typename InitOnceTrait = ThreadSafeInitOnceTrait,
199 typename DestroyTrait = LeakyInstanceTrait<T> >
202 CreateTrait, InitOnceTrait, DestroyTrait>;
203};
204
205
206template <typename T,
207 typename CreateTrait = DefaultConstructTrait<T>,
208 typename InitOnceTrait = ThreadSafeInitOnceTrait,
209 typename DestroyTrait = LeakyInstanceTrait<T> >
211 // A LazyInstance is a LazyStaticInstance.
212 using type = typename LazyStaticInstance<T, CreateTrait, InitOnceTrait,
213 DestroyTrait>::type;
214};
215
216
217template <typename T,
218 typename CreateTrait = DefaultCreateTrait<T>,
219 typename InitOnceTrait = ThreadSafeInitOnceTrait,
220 typename DestroyTrait = LeakyInstanceTrait<T> >
223 CreateTrait, InitOnceTrait, DestroyTrait>;
224};
225
226// LeakyObject<T> wraps an object of type T, which is initialized in the
227// constructor but never destructed. Thus LeakyObject<T> is trivially
228// destructible and can be used in static (lazily initialized) variables.
229template <typename T>
230class LeakyObject {
231 public:
232 template <typename... Args>
233 explicit LeakyObject(Args&&... args) {
234 new (storage_) T(std::forward<Args>(args)...);
235 }
236
237 LeakyObject(const LeakyObject&) = delete;
239
240 T* get() { return reinterpret_cast<T*>(storage_); }
241
242 private:
243 alignas(T) char storage_[sizeof(T)];
244};
245
246// Define a function which returns a pointer to a lazily initialized and never
247// destructed object of type T.
248#define DEFINE_LAZY_LEAKY_OBJECT_GETTER(T, FunctionName, ...) \
249 T* FunctionName() { \
250 static ::v8::base::LeakyObject<T> object{__VA_ARGS__}; \
251 return object.get(); \
252 }
253
254} // namespace base
255} // namespace v8
256
257#endif // V8_BASE_LAZY_INSTANCE_H_
#define T
LeakyObject & operator=(const LeakyObject &)=delete
LeakyObject(Args &&... args)
LeakyObject(const LeakyObject &)=delete
char storage_[sizeof(T)]
void CallOnce(OnceType *once, std::function< void()> init_func)
Definition once.h:90
std::atomic< uint8_t > OnceType
Definition once.h:67
V8_BASE_EXPORT int const char va_list args
Definition strings.h:23
@ ONCE_STATE_UNINITIALIZED
Definition once.h:75
@ ONCE_STATE_DONE
Definition once.h:77
static void Construct(void *allocated_ptr)
static void InitStorageUsingTrait(StorageType *storage)
static T * MutableInstance(StorageType *storage)
typename AllocationTrait::AlignmentType AlignmentType
typename AllocationTrait::StorageType StorageType
static void InitInstance(void *storage)
typename LazyStaticInstance< T, CreateTrait, InitOnceTrait, DestroyTrait >::type type
static void Init(OnceType *once, Function function, Storage storage)
static void InitStorageUsingTrait(StorageType *storage)
static T * MutableInstance(StorageType *storage)
static void Init(OnceType *once, Function function, Storage storage)