Deprecate get_weak()
authorAndrii Grynenko <andrii@fb.com>
Thu, 26 Nov 2015 20:33:16 +0000 (12:33 -0800)
committerfacebook-github-bot-0 <folly-bot@fb.com>
Thu, 26 Nov 2015 21:20:20 +0000 (13:20 -0800)
Summary: get_weak() is always used with .lock(), but try_get() is actually more performant than get_weak().lock().
Using get_weak() to store a weak_ptr and keep locking is not safe in fork scenarios.

Reviewed By: yfeldblum

Differential Revision: D2694223

fb-gh-sync-id: 908d44293ffd9b3782152d43e28d5de172d1654a

folly/Singleton.h
folly/test/SingletonTest.cpp

index 94867c02f9f456e4aafa55dde7c1b203f7a3bf14..af8dacdb6d256acc6a4796e5d526da3354189c9d 100644 (file)
@@ -486,7 +486,8 @@ class Singleton {
   // singleton, you can try to do so with a weak_ptr.  Avoid this when
   // possible but the inability to lock the weak pointer can be a
   // signal that the vault has been destroyed.
-  static std::weak_ptr<T> get_weak() {
+  static std::weak_ptr<T>
+  get_weak() __attribute__ ((__deprecated__("Replaced by try_get")))  {
     return getEntry().get_weak();
   }
 
index 575e136f5c445b4c8c93005d1a06bdab3d6b4ffe..89423d45cd109bc56a131436da893d1445ae924f 100644 (file)
@@ -391,10 +391,10 @@ TEST(Singleton, SingletonCreationError) {
   SingletonCreationError<ErrorConstructor> error_once_singleton;
 
   // first time should error out
-  EXPECT_THROW(error_once_singleton.get_weak().lock(), std::runtime_error);
+  EXPECT_THROW(error_once_singleton.try_get(), std::runtime_error);
 
   // second time it'll work fine
-  error_once_singleton.get_weak().lock();
+  error_once_singleton.try_get();
   SUCCEED();
 }
 
@@ -409,7 +409,7 @@ TEST(Singleton, SingletonConcurrencyStress) {
   std::vector<std::thread> ts;
   for (size_t i = 0; i < 100; ++i) {
     ts.emplace_back([&]() {
-        slowpoke_singleton.get_weak().lock();
+        slowpoke_singleton.try_get();
       });
   }