lazy_instance.h revision 0d205d712abd16eeed2f5d5b1052a367d23a223f
1// Copyright (c) 2012 The Chromium 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// 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
17// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
18//
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:
27//   static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
28//   void SomeMethod() {
29//     my_instance.Get().SomeMethod();  // MyClass::SomeMethod()
30//
31//     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
38#include <new>  // For placement new.
39
40#include "base/atomicops.h"
41#include "base/base_export.h"
42#include "base/logging.h"
43#include "base/memory/aligned_memory.h"
44#include "base/threading/thread_restrictions.h"
45
46// LazyInstance uses its own struct initializer-list style static
47// initialization, as base's LINKER_INITIALIZED requires a constructor and on
48// some compilers (notably gcc 4.4) this still ends up needing runtime
49// initialization.
50#ifdef __clang__
51  #define LAZY_INSTANCE_INITIALIZER {}
52#else
53  #define LAZY_INSTANCE_INITIALIZER {0, 0}
54#endif
55
56namespace base {
57
58template <typename Type>
59struct DefaultLazyInstanceTraits {
60  static const bool kRegisterOnExit = true;
61#ifndef NDEBUG
62  static const bool kAllowedToAccessOnNonjoinableThread = false;
63#endif
64
65  static Type* New(void* instance) {
66    DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u)
67        << ": Bad boy, the buffer passed to placement new is not aligned!\n"
68        "This may break some stuff like SSE-based optimizations assuming the "
69        "<Type> objects are word aligned.";
70    // Use placement new to initialize our instance in our preallocated space.
71    // The parenthesis is very important here to force POD type initialization.
72    return new (instance) Type();
73  }
74  static void Delete(Type* instance) {
75    // Explicitly call the destructor.
76    instance->~Type();
77  }
78};
79
80// We pull out some of the functionality into non-templated functions, so we
81// can implement the more complicated pieces out of line in the .cc file.
82namespace internal {
83
84// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
85// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
86// instead of:
87// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
88// my_leaky_lazy_instance;
89// (especially when T is MyLongTypeNameImplClientHolderFactory).
90// Only use this internal::-qualified verbose form to extend this traits class
91// (depending on its implementation details).
92template <typename Type>
93struct LeakyLazyInstanceTraits {
94  static const bool kRegisterOnExit = false;
95#ifndef NDEBUG
96  static const bool kAllowedToAccessOnNonjoinableThread = true;
97#endif
98
99  static Type* New(void* instance) {
100    return DefaultLazyInstanceTraits<Type>::New(instance);
101  }
102  static void Delete(Type* /* instance */) {
103  }
104};
105
106// Our AtomicWord doubles as a spinlock, where a value of
107// kBeingCreatedMarker means the spinlock is being held for creation.
108static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
109
110// Check if instance needs to be created. If so return true otherwise
111// if another thread has beat us, wait for instance to be created and
112// return false.
113BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
114
115// After creating an instance, call this to register the dtor to be called
116// at program exit and to update the atomic state to hold the |new_instance|
117BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
118                                      subtle::AtomicWord new_instance,
119                                      void* lazy_instance,
120                                      void (*dtor)(void*));
121
122}  // namespace internal
123
124template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
125class LazyInstance {
126 public:
127  // Do not define a destructor, as doing so makes LazyInstance a
128  // non-POD-struct. We don't want that because then a static initializer will
129  // be created to register the (empty) destructor with atexit() under MSVC, for
130  // example. We handle destruction of the contained Type class explicitly via
131  // the OnExit member function, where needed.
132  // ~LazyInstance() {}
133
134  // Convenience typedef to avoid having to repeat Type for leaky lazy
135  // instances.
136  typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky;
137
138  Type& Get() {
139    return *Pointer();
140  }
141
142  Type* Pointer() {
143#ifndef NDEBUG
144    // Avoid making TLS lookup on release builds.
145    if (!Traits::kAllowedToAccessOnNonjoinableThread)
146      ThreadRestrictions::AssertSingletonAllowed();
147#endif
148    // If any bit in the created mask is true, the instance has already been
149    // fully constructed.
150    static const subtle::AtomicWord kLazyInstanceCreatedMask =
151        ~internal::kLazyInstanceStateCreating;
152
153    // We will hopefully have fast access when the instance is already created.
154    // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
155    // at most once, the load is taken out of NeedsInstance() as a fast-path.
156    // The load has acquire memory ordering as a thread which sees
157    // private_instance_ > creating needs to acquire visibility over
158    // the associated data (private_buf_). Pairing Release_Store is in
159    // CompleteLazyInstance().
160    subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
161    if (!(value & kLazyInstanceCreatedMask) &&
162        internal::NeedsLazyInstance(&private_instance_)) {
163      // Create the instance in the space provided by |private_buf_|.
164      value = reinterpret_cast<subtle::AtomicWord>(
165          Traits::New(private_buf_.void_data()));
166      internal::CompleteLazyInstance(&private_instance_, value, this,
167                                     Traits::kRegisterOnExit ? OnExit : NULL);
168    }
169    return instance();
170  }
171
172  bool operator==(Type* p) {
173    switch (subtle::NoBarrier_Load(&private_instance_)) {
174      case 0:
175        return p == NULL;
176      case internal::kLazyInstanceStateCreating:
177        return static_cast<void*>(p) == private_buf_.void_data();
178      default:
179        return p == instance();
180    }
181  }
182
183  // Effectively private: member data is only public to allow the linker to
184  // statically initialize it and to maintain a POD class. DO NOT USE FROM
185  // OUTSIDE THIS CLASS.
186
187  subtle::AtomicWord private_instance_;
188  // Preallocated space for the Type instance.
189  base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> private_buf_;
190
191 private:
192  Type* instance() {
193    return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
194  }
195
196  // Adapter function for use with AtExit.  This should be called single
197  // threaded, so don't synchronize across threads.
198  // Calling OnExit while the instance is in use by other threads is a mistake.
199  static void OnExit(void* lazy_instance) {
200    LazyInstance<Type, Traits>* me =
201        reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
202    Traits::Delete(me->instance());
203    subtle::NoBarrier_Store(&me->private_instance_, 0);
204  }
205};
206
207}  // namespace base
208
209#endif  // BASE_LAZY_INSTANCE_H_
210