blob: c803fb1a65284c08c1b39e5ce04e63d3016301d2 [file] [log] [blame]
[email protected]9fc44162012-01-23 22:56:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]30039e62008-09-08 14:11:132// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// The LazyInstance<Type, Traits> class manages a single instance of Type,
6// which will be lazily created on the first time it's accessed. This class is
7// useful for places you would normally use a function-level static, but you
8// need to have guaranteed thread-safety. The Type constructor will only ever
9// be called once, even if two threads are racing to create the object. Get()
10// and Pointer() will always return the same, completely initialized instance.
11// When the instance is constructed it is registered with AtExitManager. The
12// destructor will be called on program exit.
13//
14// LazyInstance is completely thread safe, assuming that you create it safely.
15// The class was designed to be POD initialized, so it shouldn't require a
16// static constructor. It really only makes sense to declare a LazyInstance as
[email protected]6de0fd1d2011-11-15 13:31:4917// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
[email protected]30039e62008-09-08 14:11:1318//
19// LazyInstance is similar to Singleton, except it does not have the singleton
20// property. You can have multiple LazyInstance's of the same type, and each
21// will manage a unique instance. It also preallocates the space for Type, as
22// to avoid allocating the Type instance on the heap. This may help with the
23// performance of creating the instance, and reducing heap fragmentation. This
24// requires that Type be a complete type so we can determine the size.
25//
26// Example usage:
scottmg5e65e3a2017-03-08 08:48:4627// static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER;
[email protected]30039e62008-09-08 14:11:1328// void SomeMethod() {
scottmg5e65e3a2017-03-08 08:48:4629// inst.Get().SomeMethod(); // MyClass::SomeMethod()
[email protected]52a261f2009-03-03 15:01:1230//
scottmg5e65e3a2017-03-08 08:48:4631// MyClass* ptr = inst.Pointer();
[email protected]30039e62008-09-08 14:11:1332// ptr->DoDoDo(); // MyClass::DoDoDo
33// }
34
35#ifndef BASE_LAZY_INSTANCE_H_
36#define BASE_LAZY_INSTANCE_H_
37
[email protected]359d2bf2010-11-19 20:34:1838#include <new> // For placement new.
39
[email protected]30039e62008-09-08 14:11:1340#include "base/atomicops.h"
[email protected]0bea7252011-08-05 15:34:0041#include "base/base_export.h"
[email protected]b2206da52013-06-07 22:09:3242#include "base/debug/leak_annotations.h"
[email protected]e4a638f762011-10-21 19:46:0043#include "base/logging.h"
[email protected]34b99632011-01-01 01:01:0644#include "base/threading/thread_restrictions.h"
[email protected]30039e62008-09-08 14:11:1345
[email protected]6de0fd1d2011-11-15 13:31:4946// LazyInstance uses its own struct initializer-list style static
Lei Zhang46df67b2017-09-05 21:54:0947// initialization, which does not require a constructor.
[email protected]6de0fd1d2011-11-15 13:31:4948#define LAZY_INSTANCE_INITIALIZER {0}
49
[email protected]30039e62008-09-08 14:11:1350namespace base {
51
52template <typename Type>
scottmg5e65e3a2017-03-08 08:48:4653struct LazyInstanceTraitsBase {
[email protected]c1aeaac2010-03-12 15:28:4854 static Type* New(void* instance) {
brettw16289b3e2017-06-13 21:58:4055 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (alignof(Type) - 1), 0u);
[email protected]30039e62008-09-08 14:11:1356 // Use placement new to initialize our instance in our preallocated space.
57 // The parenthesis is very important here to force POD type initialization.
[email protected]c1aeaac2010-03-12 15:28:4858 return new (instance) Type();
[email protected]30039e62008-09-08 14:11:1359 }
scottmg5e65e3a2017-03-08 08:48:4660
61 static void CallDestructor(Type* instance) {
[email protected]30039e62008-09-08 14:11:1362 // Explicitly call the destructor.
[email protected]113eee02011-10-25 19:04:4863 instance->~Type();
[email protected]30039e62008-09-08 14:11:1364 }
65};
66
[email protected]67f92bc32012-01-26 01:56:1967// We pull out some of the functionality into non-templated functions, so we
68// can implement the more complicated pieces out of line in the .cc file.
69namespace internal {
70
scottmg5e65e3a2017-03-08 08:48:4671// This traits class causes destruction the contained Type at process exit via
72// AtExitManager. This is probably generally not what you want. Instead, prefer
73// Leaky below.
74template <typename Type>
75struct DestructorAtExitLazyInstanceTraits {
76 static const bool kRegisterOnExit = true;
77#if DCHECK_IS_ON()
78 static const bool kAllowedToAccessOnNonjoinableThread = false;
79#endif
80
81 static Type* New(void* instance) {
82 return LazyInstanceTraitsBase<Type>::New(instance);
83 }
84
85 static void Delete(Type* instance) {
86 LazyInstanceTraitsBase<Type>::CallDestructor(instance);
87 }
88};
89
[email protected]9fc44162012-01-23 22:56:4190// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
91// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
92// instead of:
[email protected]67f92bc32012-01-26 01:56:1993// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
94// my_leaky_lazy_instance;
[email protected]9fc44162012-01-23 22:56:4195// (especially when T is MyLongTypeNameImplClientHolderFactory).
[email protected]67f92bc32012-01-26 01:56:1996// Only use this internal::-qualified verbose form to extend this traits class
97// (depending on its implementation details).
[email protected]dcc69332010-10-21 20:41:4798template <typename Type>
99struct LeakyLazyInstanceTraits {
[email protected]113eee02011-10-25 19:04:48100 static const bool kRegisterOnExit = false;
gab190f7542016-08-01 20:03:41101#if DCHECK_IS_ON()
[email protected]359d2bf2010-11-19 20:34:18102 static const bool kAllowedToAccessOnNonjoinableThread = true;
[email protected]5a8a8062014-03-06 01:11:54103#endif
[email protected]359d2bf2010-11-19 20:34:18104
[email protected]dcc69332010-10-21 20:41:47105 static Type* New(void* instance) {
[email protected]b2206da52013-06-07 22:09:32106 ANNOTATE_SCOPED_MEMORY_LEAK;
scottmg5e65e3a2017-03-08 08:48:46107 return LazyInstanceTraitsBase<Type>::New(instance);
[email protected]dcc69332010-10-21 20:41:47108 }
[email protected]113eee02011-10-25 19:04:48109 static void Delete(Type* instance) {
110 }
[email protected]dcc69332010-10-21 20:41:47111};
112
scottmg5e65e3a2017-03-08 08:48:46113template <typename Type>
114struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {};
115
[email protected]6de0fd1d2011-11-15 13:31:49116// Our AtomicWord doubles as a spinlock, where a value of
palmer84a608b2016-11-04 22:47:45117// kLazyInstanceStateCreating means the spinlock is being held for creation.
Francois Doraya50035b2017-06-12 17:55:50118constexpr subtle::AtomicWord kLazyInstanceStateCreating = 1;
[email protected]1b651d52011-05-16 15:01:54119
[email protected]6de0fd1d2011-11-15 13:31:49120// Check if instance needs to be created. If so return true otherwise
121// if another thread has beat us, wait for instance to be created and
122// return false.
123BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
[email protected]30039e62008-09-08 14:11:13124
[email protected]6de0fd1d2011-11-15 13:31:49125// After creating an instance, call this to register the dtor to be called
126// at program exit and to update the atomic state to hold the |new_instance|
127BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
128 subtle::AtomicWord new_instance,
Francois Doraya50035b2017-06-12 17:55:50129 void (*destructor)(void*),
130 void* destructor_arg);
131
132// If |state| is uninitialized, constructs a value using |creator_func|, stores
133// it into |state| and registers |destructor| to be called with |destructor_arg|
134// as argument when the current AtExitManager goes out of scope. Then, returns
135// the value stored in |state|. It is safe to have concurrent calls to this
136// function with the same |state|.
137template <typename CreatorFunc>
138void* GetOrCreateLazyPointer(subtle::AtomicWord* state,
139 const CreatorFunc& creator_func,
140 void (*destructor)(void*),
141 void* destructor_arg) {
142 // If any bit in the created mask is true, the instance has already been
143 // fully constructed.
144 constexpr subtle::AtomicWord kLazyInstanceCreatedMask =
145 ~internal::kLazyInstanceStateCreating;
146
147 // We will hopefully have fast access when the instance is already created.
148 // Since a thread sees |state| == 0 or kLazyInstanceStateCreating at most
149 // once, the load is taken out of NeedsLazyInstance() as a fast-path. The load
150 // has acquire memory ordering as a thread which sees |state| > creating needs
151 // to acquire visibility over the associated data. Pairing Release_Store is in
152 // CompleteLazyInstance().
153 subtle::AtomicWord value = subtle::Acquire_Load(state);
154 if (!(value & kLazyInstanceCreatedMask) && NeedsLazyInstance(state)) {
155 // Create the instance in the space provided by |private_buf_|.
156 value = reinterpret_cast<subtle::AtomicWord>(creator_func());
157 CompleteLazyInstance(state, value, destructor, destructor_arg);
158 }
159 return reinterpret_cast<void*>(subtle::NoBarrier_Load(state));
160}
[email protected]1b651d52011-05-16 15:01:54161
[email protected]6de0fd1d2011-11-15 13:31:49162} // namespace internal
[email protected]30039e62008-09-08 14:11:13163
scottmg5e65e3a2017-03-08 08:48:46164template <
165 typename Type,
166 typename Traits =
167 internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
[email protected]6de0fd1d2011-11-15 13:31:49168class LazyInstance {
[email protected]30039e62008-09-08 14:11:13169 public:
[email protected]6de0fd1d2011-11-15 13:31:49170 // Do not define a destructor, as doing so makes LazyInstance a
171 // non-POD-struct. We don't want that because then a static initializer will
172 // be created to register the (empty) destructor with atexit() under MSVC, for
173 // example. We handle destruction of the contained Type class explicitly via
174 // the OnExit member function, where needed.
[email protected]1b651d52011-05-16 15:01:54175 // ~LazyInstance() {}
[email protected]30039e62008-09-08 14:11:13176
[email protected]9fc44162012-01-23 22:56:41177 // Convenience typedef to avoid having to repeat Type for leaky lazy
178 // instances.
scottmg5e65e3a2017-03-08 08:48:46179 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky;
180 typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>>
181 DestructorAtExit;
[email protected]9fc44162012-01-23 22:56:41182
[email protected]30039e62008-09-08 14:11:13183 Type& Get() {
184 return *Pointer();
185 }
186
187 Type* Pointer() {
gab190f7542016-08-01 20:03:41188#if DCHECK_IS_ON()
[email protected]3c7a7f32011-11-04 17:29:10189 // Avoid making TLS lookup on release builds.
[email protected]359d2bf2010-11-19 20:34:18190 if (!Traits::kAllowedToAccessOnNonjoinableThread)
[email protected]6de0fd1d2011-11-15 13:31:49191 ThreadRestrictions::AssertSingletonAllowed();
[email protected]3c7a7f32011-11-04 17:29:10192#endif
Francois Doraya50035b2017-06-12 17:55:50193 return static_cast<Type*>(internal::GetOrCreateLazyPointer(
194 &private_instance_,
brettw16289b3e2017-06-13 21:58:40195 [this]() { return Traits::New(private_buf_); },
Francois Doraya50035b2017-06-12 17:55:50196 Traits::kRegisterOnExit ? OnExit : nullptr, this));
[email protected]30039e62008-09-08 14:11:13197 }
198
Lukasz Anforowiczd3e19132017-12-06 19:44:27199 // Returns true if the lazy instance has been created. Unlike Get() and
200 // Pointer(), calling IsCreated() will not instantiate the object of Type.
201 bool IsCreated() {
202 // Return true (i.e. "created") if |private_instance_| is either being
203 // created right now (i.e. |private_instance_| has value of
204 // internal::kLazyInstanceStateCreating) or was already created (i.e.
205 // |private_instance_| has any other non-zero value).
206 return 0 != subtle::NoBarrier_Load(&private_instance_);
[email protected]332710b2011-02-22 19:21:59207 }
208
brettw16289b3e2017-06-13 21:58:40209 // MSVC gives a warning that the alignment expands the size of the
210 // LazyInstance struct to make the size a multiple of the alignment. This
211 // is expected in this case.
212#if defined(OS_WIN)
213#pragma warning(push)
214#pragma warning(disable: 4324)
215#endif
216
[email protected]6de0fd1d2011-11-15 13:31:49217 // Effectively private: member data is only public to allow the linker to
[email protected]cd924d62012-02-23 17:52:20218 // statically initialize it and to maintain a POD class. DO NOT USE FROM
219 // OUTSIDE THIS CLASS.
[email protected]6de0fd1d2011-11-15 13:31:49220 subtle::AtomicWord private_instance_;
brettw16289b3e2017-06-13 21:58:40221
[email protected]cd924d62012-02-23 17:52:20222 // Preallocated space for the Type instance.
brettw16289b3e2017-06-13 21:58:40223 alignas(Type) char private_buf_[sizeof(Type)];
224
225#if defined(OS_WIN)
226#pragma warning(pop)
227#endif
[email protected]6de0fd1d2011-11-15 13:31:49228
[email protected]30039e62008-09-08 14:11:13229 private:
[email protected]6de0fd1d2011-11-15 13:31:49230 Type* instance() {
231 return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
232 }
233
[email protected]625332e02010-12-14 07:48:49234 // Adapter function for use with AtExit. This should be called single
[email protected]113eee02011-10-25 19:04:48235 // threaded, so don't synchronize across threads.
[email protected]625332e02010-12-14 07:48:49236 // Calling OnExit while the instance is in use by other threads is a mistake.
237 static void OnExit(void* lazy_instance) {
238 LazyInstance<Type, Traits>* me =
239 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
[email protected]6de0fd1d2011-11-15 13:31:49240 Traits::Delete(me->instance());
[email protected]cd924d62012-02-23 17:52:20241 subtle::NoBarrier_Store(&me->private_instance_, 0);
[email protected]625332e02010-12-14 07:48:49242 }
[email protected]30039e62008-09-08 14:11:13243};
244
245} // namespace base
246
247#endif // BASE_LAZY_INSTANCE_H_