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