blob: d52b5431c29bbf46232fd89fcbce7870c3d6801c [file] [log] [blame]
fischman@chromium.org998561e2012-01-24 07:56:41 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
deanm@google.coma6deb002008-09-08 23:11:13 +09002// 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
joth@chromium.orgb24883c2011-11-15 22:31:49 +090017// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
deanm@google.coma6deb002008-09-08 23:11:13 +090018//
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:
joth@chromium.orgb24883c2011-11-15 22:31:49 +090027// static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
deanm@google.coma6deb002008-09-08 23:11:13 +090028// void SomeMethod() {
29// my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090030//
deanm@google.coma6deb002008-09-08 23:11:13 +090031// MyClass* ptr = my_instance.Pointer();
32// ptr->DoDoDo(); // MyClass::DoDoDo
33// }
34
35#ifndef BASE_LAZY_INSTANCE_H_
36#define BASE_LAZY_INSTANCE_H_
37
willchan@chromium.org25726ef2010-11-20 05:34:18 +090038#include <new> // For placement new.
39
deanm@google.coma6deb002008-09-08 23:11:13 +090040#include "base/atomicops.h"
darin@chromium.orge585bed2011-08-06 00:34:00 +090041#include "base/base_export.h"
deanm@google.coma6deb002008-09-08 23:11:13 +090042#include "base/basictypes.h"
earthdok@google.com00c0afd2013-06-08 07:09:32 +090043#include "base/debug/leak_annotations.h"
timurrrr@chromium.org4814da92011-10-22 04:46:00 +090044#include "base/logging.h"
jbates@chromium.orgdde8e302012-02-24 02:52:20 +090045#include "base/memory/aligned_memory.h"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090046#include "base/threading/thread_restrictions.h"
deanm@google.coma6deb002008-09-08 23:11:13 +090047
joth@chromium.orgb24883c2011-11-15 22:31:49 +090048// LazyInstance uses its own struct initializer-list style static
49// initialization, as base's LINKER_INITIALIZED requires a constructor and on
50// some compilers (notably gcc 4.4) this still ends up needing runtime
51// initialization.
52#define LAZY_INSTANCE_INITIALIZER {0}
53
deanm@google.coma6deb002008-09-08 23:11:13 +090054namespace base {
55
56template <typename Type>
57struct DefaultLazyInstanceTraits {
joth@chromium.org524b5ce2011-10-26 04:04:48 +090058 static const bool kRegisterOnExit = true;
thakis@chromium.org2a1f9262014-03-06 10:11:54 +090059#ifndef NDEBUG
willchan@chromium.org25726ef2010-11-20 05:34:18 +090060 static const bool kAllowedToAccessOnNonjoinableThread = false;
thakis@chromium.org2a1f9262014-03-06 10:11:54 +090061#endif
willchan@chromium.org25726ef2010-11-20 05:34:18 +090062
craig.schlenter@chromium.org0cf58332010-03-13 00:28:48 +090063 static Type* New(void* instance) {
jbates@chromium.orgdde8e302012-02-24 02:52:20 +090064 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u)
timurrrr@chromium.org4814da92011-10-22 04:46:00 +090065 << ": Bad boy, the buffer passed to placement new is not aligned!\n"
66 "This may break some stuff like SSE-based optimizations assuming the "
67 "<Type> objects are word aligned.";
deanm@google.coma6deb002008-09-08 23:11:13 +090068 // Use placement new to initialize our instance in our preallocated space.
69 // The parenthesis is very important here to force POD type initialization.
craig.schlenter@chromium.org0cf58332010-03-13 00:28:48 +090070 return new (instance) Type();
deanm@google.coma6deb002008-09-08 23:11:13 +090071 }
joth@chromium.org524b5ce2011-10-26 04:04:48 +090072 static void Delete(Type* instance) {
deanm@google.coma6deb002008-09-08 23:11:13 +090073 // Explicitly call the destructor.
joth@chromium.org524b5ce2011-10-26 04:04:48 +090074 instance->~Type();
deanm@google.coma6deb002008-09-08 23:11:13 +090075 }
76};
77
fischman@chromium.orgdfdfa902012-01-26 10:56:19 +090078// We pull out some of the functionality into non-templated functions, so we
79// can implement the more complicated pieces out of line in the .cc file.
80namespace internal {
81
fischman@chromium.org998561e2012-01-24 07:56:41 +090082// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
83// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
84// instead of:
fischman@chromium.orgdfdfa902012-01-26 10:56:19 +090085// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
86// my_leaky_lazy_instance;
fischman@chromium.org998561e2012-01-24 07:56:41 +090087// (especially when T is MyLongTypeNameImplClientHolderFactory).
fischman@chromium.orgdfdfa902012-01-26 10:56:19 +090088// Only use this internal::-qualified verbose form to extend this traits class
89// (depending on its implementation details).
evan@chromium.orga04f70c2010-10-22 05:41:47 +090090template <typename Type>
91struct LeakyLazyInstanceTraits {
joth@chromium.org524b5ce2011-10-26 04:04:48 +090092 static const bool kRegisterOnExit = false;
thakis@chromium.org2a1f9262014-03-06 10:11:54 +090093#ifndef NDEBUG
willchan@chromium.org25726ef2010-11-20 05:34:18 +090094 static const bool kAllowedToAccessOnNonjoinableThread = true;
thakis@chromium.org2a1f9262014-03-06 10:11:54 +090095#endif
willchan@chromium.org25726ef2010-11-20 05:34:18 +090096
evan@chromium.orga04f70c2010-10-22 05:41:47 +090097 static Type* New(void* instance) {
earthdok@google.com00c0afd2013-06-08 07:09:32 +090098 ANNOTATE_SCOPED_MEMORY_LEAK;
evan@chromium.orga04f70c2010-10-22 05:41:47 +090099 return DefaultLazyInstanceTraits<Type>::New(instance);
100 }
joth@chromium.org524b5ce2011-10-26 04:04:48 +0900101 static void Delete(Type* instance) {
102 }
evan@chromium.orga04f70c2010-10-22 05:41:47 +0900103};
104
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900105// Our AtomicWord doubles as a spinlock, where a value of
106// kBeingCreatedMarker means the spinlock is being held for creation.
107static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
dvyukov@google.com6beeb832011-05-17 00:01:54 +0900108
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900109// Check if instance needs to be created. If so return true otherwise
110// if another thread has beat us, wait for instance to be created and
111// return false.
112BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
deanm@google.coma6deb002008-09-08 23:11:13 +0900113
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900114// After creating an instance, call this to register the dtor to be called
115// at program exit and to update the atomic state to hold the |new_instance|
116BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
117 subtle::AtomicWord new_instance,
118 void* lazy_instance,
119 void (*dtor)(void*));
dvyukov@google.com6beeb832011-05-17 00:01:54 +0900120
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900121} // namespace internal
deanm@google.coma6deb002008-09-08 23:11:13 +0900122
123template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900124class LazyInstance {
deanm@google.coma6deb002008-09-08 23:11:13 +0900125 public:
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900126 // Do not define a destructor, as doing so makes LazyInstance a
127 // non-POD-struct. We don't want that because then a static initializer will
128 // be created to register the (empty) destructor with atexit() under MSVC, for
129 // example. We handle destruction of the contained Type class explicitly via
130 // the OnExit member function, where needed.
dvyukov@google.com6beeb832011-05-17 00:01:54 +0900131 // ~LazyInstance() {}
deanm@google.coma6deb002008-09-08 23:11:13 +0900132
fischman@chromium.org998561e2012-01-24 07:56:41 +0900133 // Convenience typedef to avoid having to repeat Type for leaky lazy
134 // instances.
fischman@chromium.orgdfdfa902012-01-26 10:56:19 +0900135 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky;
fischman@chromium.org998561e2012-01-24 07:56:41 +0900136
deanm@google.coma6deb002008-09-08 23:11:13 +0900137 Type& Get() {
138 return *Pointer();
139 }
140
141 Type* Pointer() {
joth@chromium.orgd70623d2011-11-05 02:29:10 +0900142#ifndef NDEBUG
143 // Avoid making TLS lookup on release builds.
willchan@chromium.org25726ef2010-11-20 05:34:18 +0900144 if (!Traits::kAllowedToAccessOnNonjoinableThread)
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900145 ThreadRestrictions::AssertSingletonAllowed();
joth@chromium.orgd70623d2011-11-05 02:29:10 +0900146#endif
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900147 // If any bit in the created mask is true, the instance has already been
148 // fully constructed.
149 static const subtle::AtomicWord kLazyInstanceCreatedMask =
150 ~internal::kLazyInstanceStateCreating;
willchan@chromium.org25726ef2010-11-20 05:34:18 +0900151
deanm@google.coma6deb002008-09-08 23:11:13 +0900152 // We will hopefully have fast access when the instance is already created.
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900153 // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
154 // at most once, the load is taken out of NeedsInstance() as a fast-path.
dvyukov@google.com6beeb832011-05-17 00:01:54 +0900155 // The load has acquire memory ordering as a thread which sees
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900156 // private_instance_ > creating needs to acquire visibility over
157 // the associated data (private_buf_). Pairing Release_Store is in
158 // CompleteLazyInstance().
159 subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
160 if (!(value & kLazyInstanceCreatedMask) &&
161 internal::NeedsLazyInstance(&private_instance_)) {
162 // Create the instance in the space provided by |private_buf_|.
jbates@chromium.orgdde8e302012-02-24 02:52:20 +0900163 value = reinterpret_cast<subtle::AtomicWord>(
164 Traits::New(private_buf_.void_data()));
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900165 internal::CompleteLazyInstance(&private_instance_, value, this,
166 Traits::kRegisterOnExit ? OnExit : NULL);
craig.schlenter@chromium.org0cf58332010-03-13 00:28:48 +0900167 }
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900168 return instance();
deanm@google.coma6deb002008-09-08 23:11:13 +0900169 }
170
dilmah@chromium.org19b68692011-02-23 04:21:59 +0900171 bool operator==(Type* p) {
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900172 switch (subtle::NoBarrier_Load(&private_instance_)) {
173 case 0:
dilmah@chromium.org19b68692011-02-23 04:21:59 +0900174 return p == NULL;
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900175 case internal::kLazyInstanceStateCreating:
jbates@chromium.orgdde8e302012-02-24 02:52:20 +0900176 return static_cast<void*>(p) == private_buf_.void_data();
dilmah@chromium.org19b68692011-02-23 04:21:59 +0900177 default:
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900178 return p == instance();
dilmah@chromium.org19b68692011-02-23 04:21:59 +0900179 }
180 }
181
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900182 // Effectively private: member data is only public to allow the linker to
jbates@chromium.orgdde8e302012-02-24 02:52:20 +0900183 // statically initialize it and to maintain a POD class. DO NOT USE FROM
184 // OUTSIDE THIS CLASS.
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900185
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900186 subtle::AtomicWord private_instance_;
jbates@chromium.orgdde8e302012-02-24 02:52:20 +0900187 // Preallocated space for the Type instance.
188 base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> private_buf_;
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900189
deanm@google.coma6deb002008-09-08 23:11:13 +0900190 private:
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900191 Type* instance() {
192 return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
193 }
194
satish@chromium.org2940ad12010-12-14 16:48:49 +0900195 // Adapter function for use with AtExit. This should be called single
joth@chromium.org524b5ce2011-10-26 04:04:48 +0900196 // threaded, so don't synchronize across threads.
satish@chromium.org2940ad12010-12-14 16:48:49 +0900197 // Calling OnExit while the instance is in use by other threads is a mistake.
198 static void OnExit(void* lazy_instance) {
199 LazyInstance<Type, Traits>* me =
200 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
joth@chromium.orgb24883c2011-11-15 22:31:49 +0900201 Traits::Delete(me->instance());
jbates@chromium.orgdde8e302012-02-24 02:52:20 +0900202 subtle::NoBarrier_Store(&me->private_instance_, 0);
satish@chromium.org2940ad12010-12-14 16:48:49 +0900203 }
deanm@google.coma6deb002008-09-08 23:11:13 +0900204};
205
206} // namespace base
207
208#endif // BASE_LAZY_INSTANCE_H_