lazy_instance.h revision 731df977c0511bca2206b5f333555b1205ff1f43
1// Copyright (c) 2008 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 base::LinkerInitialized constructor. 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(base::LINKER_INITIALIZED); 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#pragma once 38 39#include "base/atomicops.h" 40#include "base/basictypes.h" 41#include "base/third_party/dynamic_annotations/dynamic_annotations.h" 42 43namespace base { 44 45template <typename Type> 46struct DefaultLazyInstanceTraits { 47 static Type* New(void* instance) { 48 // Use placement new to initialize our instance in our preallocated space. 49 // The parenthesis is very important here to force POD type initialization. 50 return new (instance) Type(); 51 } 52 static void Delete(void* instance) { 53 // Explicitly call the destructor. 54 reinterpret_cast<Type*>(instance)->~Type(); 55 } 56}; 57 58template <typename Type> 59struct LeakyLazyInstanceTraits { 60 static Type* New(void* instance) { 61 return DefaultLazyInstanceTraits<Type>::New(instance); 62 } 63 // Rather than define an empty Delete function, we make Delete itself 64 // a null pointer. This allows us to completely sidestep registering 65 // this object with an AtExitManager, which allows you to use 66 // LeakyLazyInstanceTraits in contexts where you don't have an 67 // AtExitManager. 68 static void (*Delete)(void* instance); 69}; 70 71template <typename Type> 72void (*LeakyLazyInstanceTraits<Type>::Delete)(void* instance) = NULL; 73 74// We pull out some of the functionality into a non-templated base, so that we 75// can implement the more complicated pieces out of line in the .cc file. 76class LazyInstanceHelper { 77 protected: 78 enum { 79 STATE_EMPTY = 0, 80 STATE_CREATING = 1, 81 STATE_CREATED = 2 82 }; 83 84 explicit LazyInstanceHelper(LinkerInitialized x) { /* state_ is 0 */ } 85 // Declaring a destructor (even if it's empty) will cause MSVC to register a 86 // static initializer to register the empty destructor with atexit(). 87 88 // Check if instance needs to be created. If so return true otherwise 89 // if another thread has beat us, wait for instance to be created and 90 // return false. 91 bool NeedsInstance(); 92 93 // After creating an instance, call this to register the dtor to be called 94 // at program exit and to update the state to STATE_CREATED. 95 void CompleteInstance(void* instance, void (*dtor)(void*)); 96 97 base::subtle::Atomic32 state_; 98 99 private: 100 DISALLOW_COPY_AND_ASSIGN(LazyInstanceHelper); 101}; 102 103template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > 104class LazyInstance : public LazyInstanceHelper { 105 public: 106 explicit LazyInstance(LinkerInitialized x) : LazyInstanceHelper(x) { } 107 // Declaring a destructor (even if it's empty) will cause MSVC to register a 108 // static initializer to register the empty destructor with atexit(). 109 110 Type& Get() { 111 return *Pointer(); 112 } 113 114 Type* Pointer() { 115 // We will hopefully have fast access when the instance is already created. 116 if ((base::subtle::NoBarrier_Load(&state_) != STATE_CREATED) && 117 NeedsInstance()) { 118 // Create the instance in the space provided by |buf_|. 119 instance_ = Traits::New(buf_); 120 CompleteInstance(instance_, Traits::Delete); 121 } 122 123 // This annotation helps race detectors recognize correct lock-less 124 // synchronization between different threads calling Pointer(). 125 // We suggest dynamic race detection tool that "Traits::New" above 126 // and CompleteInstance(...) happens before "return instance_" below. 127 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). 128 ANNOTATE_HAPPENS_AFTER(&state_); 129 130 return instance_; 131 } 132 133 private: 134 int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance. 135 Type *instance_; 136 137 DISALLOW_COPY_AND_ASSIGN(LazyInstance); 138}; 139 140} // namespace base 141 142#endif // BASE_LAZY_INSTANCE_H_ 143