Home | History | Annotate | Download | only in base
      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>::Leaky inst = LAZY_INSTANCE_INITIALIZER;
     28 //   void SomeMethod() {
     29 //     inst.Get().SomeMethod();  // MyClass::SomeMethod()
     30 //
     31 //     MyClass* ptr = inst.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/debug/leak_annotations.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 #ifdef __clang__
     52   #define LAZY_INSTANCE_INITIALIZER {}
     53 #else
     54   #define LAZY_INSTANCE_INITIALIZER {0, 0}
     55 #endif
     56 
     57 namespace base {
     58 
     59 template <typename Type>
     60 struct LazyInstanceTraitsBase {
     61   static Type* New(void* instance) {
     62     DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u);
     63     // Use placement new to initialize our instance in our preallocated space.
     64     // The parenthesis is very important here to force POD type initialization.
     65     return new (instance) Type();
     66   }
     67 
     68   static void CallDestructor(Type* instance) {
     69     // Explicitly call the destructor.
     70     instance->~Type();
     71   }
     72 };
     73 
     74 // We pull out some of the functionality into non-templated functions, so we
     75 // can implement the more complicated pieces out of line in the .cc file.
     76 namespace internal {
     77 
     78 // This traits class causes destruction the contained Type at process exit via
     79 // AtExitManager. This is probably generally not what you want. Instead, prefer
     80 // Leaky below.
     81 template <typename Type>
     82 struct DestructorAtExitLazyInstanceTraits {
     83   static const bool kRegisterOnExit = true;
     84 #if DCHECK_IS_ON()
     85   static const bool kAllowedToAccessOnNonjoinableThread = false;
     86 #endif
     87 
     88   static Type* New(void* instance) {
     89     return LazyInstanceTraitsBase<Type>::New(instance);
     90   }
     91 
     92   static void Delete(Type* instance) {
     93     LazyInstanceTraitsBase<Type>::CallDestructor(instance);
     94   }
     95 };
     96 
     97 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
     98 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
     99 // instead of:
    100 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
    101 // my_leaky_lazy_instance;
    102 // (especially when T is MyLongTypeNameImplClientHolderFactory).
    103 // Only use this internal::-qualified verbose form to extend this traits class
    104 // (depending on its implementation details).
    105 template <typename Type>
    106 struct LeakyLazyInstanceTraits {
    107   static const bool kRegisterOnExit = false;
    108 #if DCHECK_IS_ON()
    109   static const bool kAllowedToAccessOnNonjoinableThread = true;
    110 #endif
    111 
    112   static Type* New(void* instance) {
    113     ANNOTATE_SCOPED_MEMORY_LEAK;
    114     return LazyInstanceTraitsBase<Type>::New(instance);
    115   }
    116   static void Delete(Type* instance) {
    117   }
    118 };
    119 
    120 template <typename Type>
    121 struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {};
    122 
    123 // Our AtomicWord doubles as a spinlock, where a value of
    124 // kLazyInstanceStateCreating means the spinlock is being held for creation.
    125 static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
    126 
    127 // Check if instance needs to be created. If so return true otherwise
    128 // if another thread has beat us, wait for instance to be created and
    129 // return false.
    130 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
    131 
    132 // After creating an instance, call this to register the dtor to be called
    133 // at program exit and to update the atomic state to hold the |new_instance|
    134 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
    135                                       subtle::AtomicWord new_instance,
    136                                       void* lazy_instance,
    137                                       void (*dtor)(void*));
    138 
    139 }  // namespace internal
    140 
    141 template <
    142     typename Type,
    143     typename Traits =
    144         internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
    145 class LazyInstance {
    146  public:
    147   // Do not define a destructor, as doing so makes LazyInstance a
    148   // non-POD-struct. We don't want that because then a static initializer will
    149   // be created to register the (empty) destructor with atexit() under MSVC, for
    150   // example. We handle destruction of the contained Type class explicitly via
    151   // the OnExit member function, where needed.
    152   // ~LazyInstance() {}
    153 
    154   // Convenience typedef to avoid having to repeat Type for leaky lazy
    155   // instances.
    156   typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky;
    157   typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>>
    158       DestructorAtExit;
    159 
    160   Type& Get() {
    161     return *Pointer();
    162   }
    163 
    164   Type* Pointer() {
    165 #if DCHECK_IS_ON()
    166     // Avoid making TLS lookup on release builds.
    167     if (!Traits::kAllowedToAccessOnNonjoinableThread)
    168       ThreadRestrictions::AssertSingletonAllowed();
    169 #endif
    170     // If any bit in the created mask is true, the instance has already been
    171     // fully constructed.
    172     static const subtle::AtomicWord kLazyInstanceCreatedMask =
    173         ~internal::kLazyInstanceStateCreating;
    174 
    175     // We will hopefully have fast access when the instance is already created.
    176     // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
    177     // at most once, the load is taken out of NeedsInstance() as a fast-path.
    178     // The load has acquire memory ordering as a thread which sees
    179     // private_instance_ > creating needs to acquire visibility over
    180     // the associated data (private_buf_). Pairing Release_Store is in
    181     // CompleteLazyInstance().
    182     subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
    183     if (!(value & kLazyInstanceCreatedMask) &&
    184         internal::NeedsLazyInstance(&private_instance_)) {
    185       // Create the instance in the space provided by |private_buf_|.
    186       value = reinterpret_cast<subtle::AtomicWord>(
    187           Traits::New(private_buf_.void_data()));
    188       internal::CompleteLazyInstance(&private_instance_, value, this,
    189                                      Traits::kRegisterOnExit ? OnExit : NULL);
    190     }
    191     return instance();
    192   }
    193 
    194   bool operator==(Type* p) {
    195     switch (subtle::NoBarrier_Load(&private_instance_)) {
    196       case 0:
    197         return p == NULL;
    198       case internal::kLazyInstanceStateCreating:
    199         return static_cast<void*>(p) == private_buf_.void_data();
    200       default:
    201         return p == instance();
    202     }
    203   }
    204 
    205   // Effectively private: member data is only public to allow the linker to
    206   // statically initialize it and to maintain a POD class. DO NOT USE FROM
    207   // OUTSIDE THIS CLASS.
    208 
    209   subtle::AtomicWord private_instance_;
    210   // Preallocated space for the Type instance.
    211   base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> private_buf_;
    212 
    213  private:
    214   Type* instance() {
    215     return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
    216   }
    217 
    218   // Adapter function for use with AtExit.  This should be called single
    219   // threaded, so don't synchronize across threads.
    220   // Calling OnExit while the instance is in use by other threads is a mistake.
    221   static void OnExit(void* lazy_instance) {
    222     LazyInstance<Type, Traits>* me =
    223         reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
    224     Traits::Delete(me->instance());
    225     subtle::NoBarrier_Store(&me->private_instance_, 0);
    226   }
    227 };
    228 
    229 }  // namespace base
    230 
    231 #endif  // BASE_LAZY_INSTANCE_H_
    232