lazy-instance.h 8.56 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

// The LazyInstance<Type, Traits> class manages a single instance of Type,
// which will be lazily created on the first time it's accessed.  This class is
// useful for places you would normally use a function-level static, but you
// need to have guaranteed thread-safety.  The Type constructor will only ever
// be called once, even if two threads are racing to create the object.  Get()
// and Pointer() will always return the same, completely initialized instance.
//
// LazyInstance is completely thread safe, assuming that you create it safely.
// The class was designed to be POD initialized, so it shouldn't require a
// static constructor.  It really only makes sense to declare a LazyInstance as
// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
//
// LazyInstance is similar to Singleton, except it does not have the singleton
// property.  You can have multiple LazyInstance's of the same type, and each
// will manage a unique instance.  It also preallocates the space for Type, as
// to avoid allocating the Type instance on the heap.  This may help with the
// performance of creating the instance, and reducing heap fragmentation.  This
// requires that Type be a complete type so we can determine the size. See
// notes for advanced users below for more explanations.
//
// Example usage:
//   static LazyInstance<MyClass>::type my_instance = LAZY_INSTANCE_INITIALIZER;
//   void SomeMethod() {
//     my_instance.Get().SomeMethod();  // MyClass::SomeMethod()
//
//     MyClass* ptr = my_instance.Pointer();
//     ptr->DoDoDo();  // MyClass::DoDoDo
//   }
//
// Additionally you can override the way your instance is constructed by
// providing your own trait:
// Example usage:
//   struct MyCreateTrait {
38
//     static void Construct(void* allocated_ptr) {
39 40 41 42 43 44
//       new (allocated_ptr) MyClass(/* extra parameters... */);
//     }
//   };
//   static LazyInstance<MyClass, MyCreateTrait>::type my_instance =
//      LAZY_INSTANCE_INITIALIZER;
//
45
// WARNINGS:
46 47
// - This implementation of LazyInstance IS THREAD-SAFE by default. See
//   SingleThreadInitOnceTrait if you don't care about thread safety.
48 49 50
// - Lazy initialization comes with a cost. Make sure that you don't use it on
//   critical path. Consider adding your initialization code to a function
//   which is explicitly called once.
51
//
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// Notes for advanced users:
// LazyInstance can actually be used in two different ways:
//
// - "Static mode" which is the default mode since it is the most efficient
//   (no extra heap allocation). In this mode, the instance is statically
//   allocated (stored in the global data section at compile time).
//   The macro LAZY_STATIC_INSTANCE_INITIALIZER (= LAZY_INSTANCE_INITIALIZER)
//   must be used to initialize static lazy instances.
//
// - "Dynamic mode". In this mode, the instance is dynamically allocated and
//   constructed (using new) by default. This mode is useful if you have to
//   deal with some code already allocating the instance for you (e.g.
//   OS::Mutex() which returns a new private OS-dependent subclass of Mutex).
//   The macro LAZY_DYNAMIC_INSTANCE_INITIALIZER must be used to initialize
//   dynamic lazy instances.

68 69
#ifndef V8_BASE_LAZY_INSTANCE_H_
#define V8_BASE_LAZY_INSTANCE_H_
70

71 72
#include <type_traits>

73
#include "src/base/macros.h"
74
#include "src/base/once.h"
75 76

namespace v8 {
77
namespace base {
78

79
#define LAZY_STATIC_INSTANCE_INITIALIZER { V8_ONCE_INIT, { {} } }
80 81 82 83 84 85 86 87 88 89 90 91 92 93
#define LAZY_DYNAMIC_INSTANCE_INITIALIZER { V8_ONCE_INIT, 0 }

// Default to static mode.
#define LAZY_INSTANCE_INITIALIZER LAZY_STATIC_INSTANCE_INITIALIZER


template <typename T>
struct LeakyInstanceTrait {
  static void Destroy(T* /* instance */) {}
};


// Traits that define how an instance is allocated and accessed.

94

95 96
template <typename T>
struct StaticallyAllocatedInstanceTrait {
97 98
  using StorageType =
      typename std::aligned_storage<sizeof(T), alignof(T)>::type;
99 100 101 102 103 104 105

  static T* MutableInstance(StorageType* storage) {
    return reinterpret_cast<T*>(storage);
  }

  template <typename ConstructTrait>
  static void InitStorageUsingTrait(StorageType* storage) {
106
    ConstructTrait::Construct(storage);
107 108 109 110 111 112
  }
};


template <typename T>
struct DynamicallyAllocatedInstanceTrait {
113
  using StorageType = T*;
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

  static T* MutableInstance(StorageType* storage) {
    return *storage;
  }

  template <typename CreateTrait>
  static void InitStorageUsingTrait(StorageType* storage) {
    *storage = CreateTrait::Create();
  }
};


template <typename T>
struct DefaultConstructTrait {
  // Constructs the provided object which was already allocated.
129
  static void Construct(void* allocated_ptr) { new (allocated_ptr) T(); }
130 131 132 133 134 135 136 137 138 139 140
};


template <typename T>
struct DefaultCreateTrait {
  static T* Create() {
    return new T();
  }
};


141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
struct ThreadSafeInitOnceTrait {
  template <typename Function, typename Storage>
  static void Init(OnceType* once, Function function, Storage storage) {
    CallOnce(once, function, storage);
  }
};


// Initialization trait for users who don't care about thread-safety.
struct SingleThreadInitOnceTrait {
  template <typename Function, typename Storage>
  static void Init(OnceType* once, Function function, Storage storage) {
    if (*once == ONCE_STATE_UNINITIALIZED) {
      function(storage);
      *once = ONCE_STATE_DONE;
    }
  }
};


161 162
// TODO(pliard): Handle instances destruction (using global destructors).
template <typename T, typename AllocationTrait, typename CreateTrait,
163
          typename InitOnceTrait, typename DestroyTrait  /* not used yet. */>
164 165
struct LazyInstanceImpl {
 public:
166
  using StorageType = typename AllocationTrait::StorageType;
167 168

 private:
169 170 171
  static void InitInstance(void* storage) {
    AllocationTrait::template InitStorageUsingTrait<CreateTrait>(
        static_cast<StorageType*>(storage));
172 173 174
  }

  void Init() const {
175
    InitOnceTrait::Init(&once_, &InitInstance, static_cast<void*>(&storage_));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  }

 public:
  T* Pointer() {
    Init();
    return AllocationTrait::MutableInstance(&storage_);
  }

  const T& Get() const {
    Init();
    return *AllocationTrait::MutableInstance(&storage_);
  }

  mutable OnceType once_;
  // Note that the previous field, OnceType, is an AtomicWord which guarantees
191 192
  // 4-byte alignment of the storage field below. If compiling with GCC (>4.2),
  // the LAZY_ALIGN macro above will guarantee correctness for any alignment.
193 194 195 196 197 198
  mutable StorageType storage_;
};


template <typename T,
          typename CreateTrait = DefaultConstructTrait<T>,
199
          typename InitOnceTrait = ThreadSafeInitOnceTrait,
200 201
          typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyStaticInstance {
202 203
  using type = LazyInstanceImpl<T, StaticallyAllocatedInstanceTrait<T>,
                                CreateTrait, InitOnceTrait, DestroyTrait>;
204 205 206 207 208
};


template <typename T,
          typename CreateTrait = DefaultConstructTrait<T>,
209
          typename InitOnceTrait = ThreadSafeInitOnceTrait,
210 211 212
          typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyInstance {
  // A LazyInstance is a LazyStaticInstance.
213 214
  using type = typename LazyStaticInstance<T, CreateTrait, InitOnceTrait,
                                           DestroyTrait>::type;
215 216 217 218
};


template <typename T,
219
          typename CreateTrait = DefaultCreateTrait<T>,
220
          typename InitOnceTrait = ThreadSafeInitOnceTrait,
221 222
          typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyDynamicInstance {
223 224
  using type = LazyInstanceImpl<T, DynamicallyAllocatedInstanceTrait<T>,
                                CreateTrait, InitOnceTrait, DestroyTrait>;
225 226
};

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
// LeakyObject<T> wraps an object of type T, which is initialized in the
// constructor but never destructed. Thus LeakyObject<T> is trivially
// destructible and can be used in static (lazily initialized) variables.
template <typename T>
class LeakyObject {
 public:
  template <typename... Args>
  explicit LeakyObject(Args&&... args) {
    new (&storage_) T(std::forward<Args>(args)...);
  }

  T* get() { return reinterpret_cast<T*>(&storage_); }

 private:
  typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;

  DISALLOW_COPY_AND_ASSIGN(LeakyObject);
};

// Define a function which returns a pointer to a lazily initialized and never
// destructed object of type T.
#define DEFINE_LAZY_LEAKY_OBJECT_GETTER(T, FunctionName, ...) \
  T* FunctionName() {                                         \
    static ::v8::base::LeakyObject<T> object{__VA_ARGS__};    \
    return object.get();                                      \
  }

254 255
}  // namespace base
}  // namespace v8
256

257
#endif  // V8_BASE_LAZY_INSTANCE_H_