- add sources.
[platform/framework/web/crosswalk.git] / src / base / memory / singleton.h
1 // Copyright (c) 2011 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 // PLEASE READ: Do you really need a singleton?
6 //
7 // Singletons make it hard to determine the lifetime of an object, which can
8 // lead to buggy code and spurious crashes.
9 //
10 // Instead of adding another singleton into the mix, try to identify either:
11 //   a) An existing singleton that can manage your object's lifetime
12 //   b) Locations where you can deterministically create the object and pass
13 //      into other objects
14 //
15 // If you absolutely need a singleton, please keep them as trivial as possible
16 // and ideally a leaf dependency. Singletons get problematic when they attempt
17 // to do too much in their destructor or have circular dependencies.
18
19 #ifndef BASE_MEMORY_SINGLETON_H_
20 #define BASE_MEMORY_SINGLETON_H_
21
22 #include "base/at_exit.h"
23 #include "base/atomicops.h"
24 #include "base/base_export.h"
25 #include "base/memory/aligned_memory.h"
26 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
27 #include "base/threading/thread_restrictions.h"
28
29 namespace base {
30 namespace internal {
31
32 // Our AtomicWord doubles as a spinlock, where a value of
33 // kBeingCreatedMarker means the spinlock is being held for creation.
34 static const subtle::AtomicWord kBeingCreatedMarker = 1;
35
36 // We pull out some of the functionality into a non-templated function, so that
37 // we can implement the more complicated pieces out of line in the .cc file.
38 BASE_EXPORT subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance);
39
40 }  // namespace internal
41 }  // namespace base
42
43 // TODO(joth): Move more of this file into namespace base
44
45 // Default traits for Singleton<Type>. Calls operator new and operator delete on
46 // the object. Registers automatic deletion at process exit.
47 // Overload if you need arguments or another memory allocation function.
48 template<typename Type>
49 struct DefaultSingletonTraits {
50   // Allocates the object.
51   static Type* New() {
52     // The parenthesis is very important here; it forces POD type
53     // initialization.
54     return new Type();
55   }
56
57   // Destroys the object.
58   static void Delete(Type* x) {
59     delete x;
60   }
61
62   // Set to true to automatically register deletion of the object on process
63   // exit. See below for the required call that makes this happen.
64   static const bool kRegisterAtExit = true;
65
66   // Set to false to disallow access on a non-joinable thread.  This is
67   // different from kRegisterAtExit because StaticMemorySingletonTraits allows
68   // access on non-joinable threads, and gracefully handles this.
69   static const bool kAllowedToAccessOnNonjoinableThread = false;
70 };
71
72
73 // Alternate traits for use with the Singleton<Type>.  Identical to
74 // DefaultSingletonTraits except that the Singleton will not be cleaned up
75 // at exit.
76 template<typename Type>
77 struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
78   static const bool kRegisterAtExit = false;
79   static const bool kAllowedToAccessOnNonjoinableThread = true;
80 };
81
82
83 // Alternate traits for use with the Singleton<Type>.  Allocates memory
84 // for the singleton instance from a static buffer.  The singleton will
85 // be cleaned up at exit, but can't be revived after destruction unless
86 // the Resurrect() method is called.
87 //
88 // This is useful for a certain category of things, notably logging and
89 // tracing, where the singleton instance is of a type carefully constructed to
90 // be safe to access post-destruction.
91 // In logging and tracing you'll typically get stray calls at odd times, like
92 // during static destruction, thread teardown and the like, and there's a
93 // termination race on the heap-based singleton - e.g. if one thread calls
94 // get(), but then another thread initiates AtExit processing, the first thread
95 // may call into an object residing in unallocated memory. If the instance is
96 // allocated from the data segment, then this is survivable.
97 //
98 // The destructor is to deallocate system resources, in this case to unregister
99 // a callback the system will invoke when logging levels change. Note that
100 // this is also used in e.g. Chrome Frame, where you have to allow for the
101 // possibility of loading briefly into someone else's process space, and
102 // so leaking is not an option, as that would sabotage the state of your host
103 // process once you've unloaded.
104 template <typename Type>
105 struct StaticMemorySingletonTraits {
106   // WARNING: User has to deal with get() in the singleton class
107   // this is traits for returning NULL.
108   static Type* New() {
109     // Only constructs once and returns pointer; otherwise returns NULL.
110     if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1))
111       return NULL;
112
113     return new(buffer_.void_data()) Type();
114   }
115
116   static void Delete(Type* p) {
117     if (p != NULL)
118       p->Type::~Type();
119   }
120
121   static const bool kRegisterAtExit = true;
122   static const bool kAllowedToAccessOnNonjoinableThread = true;
123
124   // Exposed for unittesting.
125   static void Resurrect() {
126     base::subtle::NoBarrier_Store(&dead_, 0);
127   }
128
129  private:
130   static base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_;
131   // Signal the object was already deleted, so it is not revived.
132   static base::subtle::Atomic32 dead_;
133 };
134
135 template <typename Type> base::AlignedMemory<sizeof(Type), ALIGNOF(Type)>
136     StaticMemorySingletonTraits<Type>::buffer_;
137 template <typename Type> base::subtle::Atomic32
138     StaticMemorySingletonTraits<Type>::dead_ = 0;
139
140 // The Singleton<Type, Traits, DifferentiatingType> class manages a single
141 // instance of Type which will be created on first use and will be destroyed at
142 // normal process exit). The Trait::Delete function will not be called on
143 // abnormal process exit.
144 //
145 // DifferentiatingType is used as a key to differentiate two different
146 // singletons having the same memory allocation functions but serving a
147 // different purpose. This is mainly used for Locks serving different purposes.
148 //
149 // Example usage:
150 //
151 // In your header:
152 //   template <typename T> struct DefaultSingletonTraits;
153 //   class FooClass {
154 //    public:
155 //     static FooClass* GetInstance();  <-- See comment below on this.
156 //     void Bar() { ... }
157 //    private:
158 //     FooClass() { ... }
159 //     friend struct DefaultSingletonTraits<FooClass>;
160 //
161 //     DISALLOW_COPY_AND_ASSIGN(FooClass);
162 //   };
163 //
164 // In your source file:
165 //  #include "base/memory/singleton.h"
166 //  FooClass* FooClass::GetInstance() {
167 //    return Singleton<FooClass>::get();
168 //  }
169 //
170 // And to call methods on FooClass:
171 //   FooClass::GetInstance()->Bar();
172 //
173 // NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
174 // and it is important that FooClass::GetInstance() is not inlined in the
175 // header. This makes sure that when source files from multiple targets include
176 // this header they don't end up with different copies of the inlined code
177 // creating multiple copies of the singleton.
178 //
179 // Singleton<> has no non-static members and doesn't need to actually be
180 // instantiated.
181 //
182 // This class is itself thread-safe. The underlying Type must of course be
183 // thread-safe if you want to use it concurrently. Two parameters may be tuned
184 // depending on the user's requirements.
185 //
186 // Glossary:
187 //   RAE = kRegisterAtExit
188 //
189 // On every platform, if Traits::RAE is true, the singleton will be destroyed at
190 // process exit. More precisely it uses base::AtExitManager which requires an
191 // object of this type to be instantiated. AtExitManager mimics the semantics
192 // of atexit() such as LIFO order but under Windows is safer to call. For more
193 // information see at_exit.h.
194 //
195 // If Traits::RAE is false, the singleton will not be freed at process exit,
196 // thus the singleton will be leaked if it is ever accessed. Traits::RAE
197 // shouldn't be false unless absolutely necessary. Remember that the heap where
198 // the object is allocated may be destroyed by the CRT anyway.
199 //
200 // Caveats:
201 // (a) Every call to get(), operator->() and operator*() incurs some overhead
202 //     (16ns on my P4/2.8GHz) to check whether the object has already been
203 //     initialized.  You may wish to cache the result of get(); it will not
204 //     change.
205 //
206 // (b) Your factory function must never throw an exception. This class is not
207 //     exception-safe.
208 //
209 template <typename Type,
210           typename Traits = DefaultSingletonTraits<Type>,
211           typename DifferentiatingType = Type>
212 class Singleton {
213  private:
214   // Classes using the Singleton<T> pattern should declare a GetInstance()
215   // method and call Singleton::get() from within that.
216   friend Type* Type::GetInstance();
217
218   // Allow TraceLog tests to test tracing after OnExit.
219   friend class DeleteTraceLogForTesting;
220
221   // This class is safe to be constructed and copy-constructed since it has no
222   // member.
223
224   // Return a pointer to the one true instance of the class.
225   static Type* get() {
226 #ifndef NDEBUG
227     // Avoid making TLS lookup on release builds.
228     if (!Traits::kAllowedToAccessOnNonjoinableThread)
229       base::ThreadRestrictions::AssertSingletonAllowed();
230 #endif
231
232     base::subtle::AtomicWord value = base::subtle::NoBarrier_Load(&instance_);
233     if (value != 0 && value != base::internal::kBeingCreatedMarker) {
234       // See the corresponding HAPPENS_BEFORE below.
235       ANNOTATE_HAPPENS_AFTER(&instance_);
236       return reinterpret_cast<Type*>(value);
237     }
238
239     // Object isn't created yet, maybe we will get to create it, let's try...
240     if (base::subtle::Acquire_CompareAndSwap(
241           &instance_, 0, base::internal::kBeingCreatedMarker) == 0) {
242       // instance_ was NULL and is now kBeingCreatedMarker.  Only one thread
243       // will ever get here.  Threads might be spinning on us, and they will
244       // stop right after we do this store.
245       Type* newval = Traits::New();
246
247       // This annotation helps race detectors recognize correct lock-less
248       // synchronization between different threads calling get().
249       // See the corresponding HAPPENS_AFTER below and above.
250       ANNOTATE_HAPPENS_BEFORE(&instance_);
251       base::subtle::Release_Store(
252           &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval));
253
254       if (newval != NULL && Traits::kRegisterAtExit)
255         base::AtExitManager::RegisterCallback(OnExit, NULL);
256
257       return newval;
258     }
259
260     // We hit a race. Wait for the other thread to complete it.
261     value = base::internal::WaitForInstance(&instance_);
262
263     // See the corresponding HAPPENS_BEFORE above.
264     ANNOTATE_HAPPENS_AFTER(&instance_);
265     return reinterpret_cast<Type*>(value);
266   }
267
268   // Adapter function for use with AtExit().  This should be called single
269   // threaded, so don't use atomic operations.
270   // Calling OnExit while singleton is in use by other threads is a mistake.
271   static void OnExit(void* /*unused*/) {
272     // AtExit should only ever be register after the singleton instance was
273     // created.  We should only ever get here with a valid instance_ pointer.
274     Traits::Delete(
275         reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_)));
276     instance_ = 0;
277   }
278   static base::subtle::AtomicWord instance_;
279 };
280
281 template <typename Type, typename Traits, typename DifferentiatingType>
282 base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::
283     instance_ = 0;
284
285 #endif  // BASE_MEMORY_SINGLETON_H_