blob: 4ed471a09bf925ce0598ec78521bb5e8f3bcfce0 [file] [log] [blame]
[email protected]9fc44162012-01-23 22:56:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]30039e62008-09-08 14:11:132// 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
[email protected]6de0fd1d2011-11-15 13:31:4917// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
[email protected]30039e62008-09-08 14:11:1318//
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:
[email protected]6de0fd1d2011-11-15 13:31:4927// static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
[email protected]30039e62008-09-08 14:11:1328// void SomeMethod() {
29// my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
[email protected]52a261f2009-03-03 15:01:1230//
[email protected]30039e62008-09-08 14:11:1331// MyClass* ptr = my_instance.Pointer();
32// ptr->DoDoDo(); // MyClass::DoDoDo
33// }
34
35#ifndef BASE_LAZY_INSTANCE_H_
36#define BASE_LAZY_INSTANCE_H_
[email protected]32b76ef2010-07-26 23:08:2437#pragma once
[email protected]30039e62008-09-08 14:11:1338
[email protected]359d2bf2010-11-19 20:34:1839#include <new> // For placement new.
40
[email protected]30039e62008-09-08 14:11:1341#include "base/atomicops.h"
[email protected]0bea7252011-08-05 15:34:0042#include "base/base_export.h"
[email protected]30039e62008-09-08 14:11:1343#include "base/basictypes.h"
[email protected]e4a638f762011-10-21 19:46:0044#include "base/logging.h"
[email protected]ee857512010-05-14 08:24:4245#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
[email protected]34b99632011-01-01 01:01:0646#include "base/threading/thread_restrictions.h"
[email protected]30039e62008-09-08 14:11:1347
[email protected]6de0fd1d2011-11-15 13:31:4948// 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
[email protected]30039e62008-09-08 14:11:1354namespace base {
55
56template <typename Type>
57struct DefaultLazyInstanceTraits {
[email protected]113eee02011-10-25 19:04:4858 static const bool kRegisterOnExit = true;
[email protected]359d2bf2010-11-19 20:34:1859 static const bool kAllowedToAccessOnNonjoinableThread = false;
60
[email protected]c1aeaac2010-03-12 15:28:4861 static Type* New(void* instance) {
[email protected]e4a638f762011-10-21 19:46:0062 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) % sizeof(instance), 0u)
63 << ": Bad boy, the buffer passed to placement new is not aligned!\n"
64 "This may break some stuff like SSE-based optimizations assuming the "
65 "<Type> objects are word aligned.";
[email protected]30039e62008-09-08 14:11:1366 // Use placement new to initialize our instance in our preallocated space.
67 // The parenthesis is very important here to force POD type initialization.
[email protected]c1aeaac2010-03-12 15:28:4868 return new (instance) Type();
[email protected]30039e62008-09-08 14:11:1369 }
[email protected]113eee02011-10-25 19:04:4870 static void Delete(Type* instance) {
[email protected]30039e62008-09-08 14:11:1371 // Explicitly call the destructor.
[email protected]113eee02011-10-25 19:04:4872 instance->~Type();
[email protected]30039e62008-09-08 14:11:1373 }
74};
75
[email protected]9fc44162012-01-23 22:56:4176// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
77// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
78// instead of:
79// base::LazyInstance<T, LeakyLazyInstanceTraits<T> > my_leaky_lazy_instance;
80// (especially when T is MyLongTypeNameImplClientHolderFactory).
[email protected]dcc69332010-10-21 20:41:4781template <typename Type>
82struct LeakyLazyInstanceTraits {
[email protected]113eee02011-10-25 19:04:4883 static const bool kRegisterOnExit = false;
[email protected]359d2bf2010-11-19 20:34:1884 static const bool kAllowedToAccessOnNonjoinableThread = true;
85
[email protected]dcc69332010-10-21 20:41:4786 static Type* New(void* instance) {
87 return DefaultLazyInstanceTraits<Type>::New(instance);
88 }
[email protected]113eee02011-10-25 19:04:4889 static void Delete(Type* instance) {
90 }
[email protected]dcc69332010-10-21 20:41:4791};
92
[email protected]6de0fd1d2011-11-15 13:31:4993// We pull out some of the functionality into non-templated functions, so we
[email protected]30039e62008-09-08 14:11:1394// can implement the more complicated pieces out of line in the .cc file.
[email protected]6de0fd1d2011-11-15 13:31:4995namespace internal {
[email protected]30039e62008-09-08 14:11:1396
[email protected]6de0fd1d2011-11-15 13:31:4997// Our AtomicWord doubles as a spinlock, where a value of
98// kBeingCreatedMarker means the spinlock is being held for creation.
99static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
[email protected]1b651d52011-05-16 15:01:54100
[email protected]6de0fd1d2011-11-15 13:31:49101// Check if instance needs to be created. If so return true otherwise
102// if another thread has beat us, wait for instance to be created and
103// return false.
104BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
[email protected]30039e62008-09-08 14:11:13105
[email protected]6de0fd1d2011-11-15 13:31:49106// After creating an instance, call this to register the dtor to be called
107// at program exit and to update the atomic state to hold the |new_instance|
108BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
109 subtle::AtomicWord new_instance,
110 void* lazy_instance,
111 void (*dtor)(void*));
[email protected]1b651d52011-05-16 15:01:54112
[email protected]6de0fd1d2011-11-15 13:31:49113} // namespace internal
[email protected]30039e62008-09-08 14:11:13114
115template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
[email protected]6de0fd1d2011-11-15 13:31:49116class LazyInstance {
[email protected]30039e62008-09-08 14:11:13117 public:
[email protected]6de0fd1d2011-11-15 13:31:49118 // Do not define a destructor, as doing so makes LazyInstance a
119 // non-POD-struct. We don't want that because then a static initializer will
120 // be created to register the (empty) destructor with atexit() under MSVC, for
121 // example. We handle destruction of the contained Type class explicitly via
122 // the OnExit member function, where needed.
[email protected]1b651d52011-05-16 15:01:54123 // ~LazyInstance() {}
[email protected]30039e62008-09-08 14:11:13124
[email protected]9fc44162012-01-23 22:56:41125 // Convenience typedef to avoid having to repeat Type for leaky lazy
126 // instances.
127 typedef LazyInstance<Type, LeakyLazyInstanceTraits<Type> > Leaky;
128
[email protected]30039e62008-09-08 14:11:13129 Type& Get() {
130 return *Pointer();
131 }
132
133 Type* Pointer() {
[email protected]3c7a7f32011-11-04 17:29:10134#ifndef NDEBUG
135 // Avoid making TLS lookup on release builds.
[email protected]359d2bf2010-11-19 20:34:18136 if (!Traits::kAllowedToAccessOnNonjoinableThread)
[email protected]6de0fd1d2011-11-15 13:31:49137 ThreadRestrictions::AssertSingletonAllowed();
[email protected]3c7a7f32011-11-04 17:29:10138#endif
[email protected]6de0fd1d2011-11-15 13:31:49139 // If any bit in the created mask is true, the instance has already been
140 // fully constructed.
141 static const subtle::AtomicWord kLazyInstanceCreatedMask =
142 ~internal::kLazyInstanceStateCreating;
[email protected]359d2bf2010-11-19 20:34:18143
[email protected]30039e62008-09-08 14:11:13144 // We will hopefully have fast access when the instance is already created.
[email protected]6de0fd1d2011-11-15 13:31:49145 // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
146 // at most once, the load is taken out of NeedsInstance() as a fast-path.
[email protected]1b651d52011-05-16 15:01:54147 // The load has acquire memory ordering as a thread which sees
[email protected]6de0fd1d2011-11-15 13:31:49148 // private_instance_ > creating needs to acquire visibility over
149 // the associated data (private_buf_). Pairing Release_Store is in
150 // CompleteLazyInstance().
151 subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
152 if (!(value & kLazyInstanceCreatedMask) &&
153 internal::NeedsLazyInstance(&private_instance_)) {
154 // Create the instance in the space provided by |private_buf_|.
155 value = reinterpret_cast<subtle::AtomicWord>(Traits::New(private_buf_));
156 internal::CompleteLazyInstance(&private_instance_, value, this,
157 Traits::kRegisterOnExit ? OnExit : NULL);
[email protected]c1aeaac2010-03-12 15:28:48158 }
[email protected]30039e62008-09-08 14:11:13159
[email protected]001b6942009-06-26 11:28:03160 // This annotation helps race detectors recognize correct lock-less
161 // synchronization between different threads calling Pointer().
[email protected]c1aeaac2010-03-12 15:28:48162 // We suggest dynamic race detection tool that "Traits::New" above
[email protected]6de0fd1d2011-11-15 13:31:49163 // and CompleteLazyInstance(...) happens before "return instance()" below.
164 // See the corresponding HAPPENS_BEFORE in CompleteLazyInstance(...).
165 ANNOTATE_HAPPENS_AFTER(&private_instance_);
166 return instance();
[email protected]30039e62008-09-08 14:11:13167 }
168
[email protected]332710b2011-02-22 19:21:59169 bool operator==(Type* p) {
[email protected]6de0fd1d2011-11-15 13:31:49170 switch (subtle::NoBarrier_Load(&private_instance_)) {
171 case 0:
[email protected]332710b2011-02-22 19:21:59172 return p == NULL;
[email protected]6de0fd1d2011-11-15 13:31:49173 case internal::kLazyInstanceStateCreating:
174 return static_cast<int8*>(static_cast<void*>(p)) == private_buf_;
[email protected]332710b2011-02-22 19:21:59175 default:
[email protected]6de0fd1d2011-11-15 13:31:49176 return p == instance();
[email protected]332710b2011-02-22 19:21:59177 }
178 }
179
[email protected]6de0fd1d2011-11-15 13:31:49180 // Effectively private: member data is only public to allow the linker to
181 // statically initialize it. DO NOT USE FROM OUTSIDE THIS CLASS.
182
183 // Note this must use AtomicWord, not Atomic32, to ensure correct alignment
184 // of |private_buf_| on 64 bit architectures. (This member must be first to
185 // allow the syntax used in LAZY_INSTANCE_INITIALIZER to work correctly.)
186 subtle::AtomicWord private_instance_;
187 int8 private_buf_[sizeof(Type)]; // Preallocated space for the Type instance.
188
[email protected]30039e62008-09-08 14:11:13189 private:
[email protected]6de0fd1d2011-11-15 13:31:49190 Type* instance() {
191 return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
192 }
193
[email protected]625332e02010-12-14 07:48:49194 // Adapter function for use with AtExit. This should be called single
[email protected]113eee02011-10-25 19:04:48195 // threaded, so don't synchronize across threads.
[email protected]625332e02010-12-14 07:48:49196 // Calling OnExit while the instance is in use by other threads is a mistake.
197 static void OnExit(void* lazy_instance) {
198 LazyInstance<Type, Traits>* me =
199 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
[email protected]6de0fd1d2011-11-15 13:31:49200 Traits::Delete(me->instance());
201 subtle::Release_Store(&me->private_instance_, 0);
[email protected]625332e02010-12-14 07:48:49202 }
[email protected]30039e62008-09-08 14:11:13203};
204
205} // namespace base
206
207#endif // BASE_LAZY_INSTANCE_H_