blob: 70b4f11ffa60ca252f5a5d7b69ed047851ea41ca [file] [log] [blame]
jhawkins@chromium.org4a310212012-01-04 04:36:57 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
mbelshe@google.com877d2032008-10-23 08:09:21 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
6#define BASE_OBSERVER_LIST_THREADSAFE_H_
7
erg@chromium.org6f206e72010-07-15 03:58:17 +09008#include <algorithm>
erg@chromium.orga7528522010-07-16 02:23:23 +09009#include <map>
mbelshe@google.com877d2032008-10-23 08:09:21 +090010
11#include "base/basictypes.h"
jhawkins@chromium.org22d67562011-10-13 05:26:50 +090012#include "base/bind.h"
ajwong@chromium.org8e2e3002011-09-22 03:05:41 +090013#include "base/location.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090014#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090015#include "base/memory/ref_counted.h"
avi@chromium.orga043a862013-07-18 17:12:40 +090016#include "base/message_loop/message_loop.h"
brettw@chromium.orgab2678f2013-06-11 05:56:28 +090017#include "base/message_loop/message_loop_proxy.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090018#include "base/observer_list.h"
tfarina@chromium.orge2903a52013-03-17 14:52:05 +090019#include "base/stl_util.h"
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +090020#include "base/threading/platform_thread.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090021
22///////////////////////////////////////////////////////////////////////////////
23//
24// OVERVIEW:
25//
26// A thread-safe container for a list of observers.
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090027// This is similar to the observer_list (see observer_list.h), but it
mbelshe@google.com877d2032008-10-23 08:09:21 +090028// is more robust for multi-threaded situations.
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090029//
mbelshe@google.com877d2032008-10-23 08:09:21 +090030// The following use cases are supported:
31// * Observers can register for notifications from any thread.
32// Callbacks to the observer will occur on the same thread where
33// the observer initially called AddObserver() from.
pkasting@chromium.orgaed4e582010-06-26 06:30:38 +090034// * Any thread may trigger a notification via Notify().
mbelshe@google.com877d2032008-10-23 08:09:21 +090035// * Observers can remove themselves from the observer list inside
36// of a callback.
37// * If one thread is notifying observers concurrently with an observer
38// removing itself from the observer list, the notifications will
39// be silently dropped.
40//
41// The drawback of the threadsafe observer list is that notifications
42// are not as real-time as the non-threadsafe version of this class.
43// Notifications will always be done via PostTask() to another thread,
44// whereas with the non-thread-safe observer_list, notifications happen
45// synchronously and immediately.
46//
47// IMPLEMENTATION NOTES
48// The ObserverListThreadSafe maintains an ObserverList for each thread
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090049// which uses the ThreadSafeObserver. When Notifying the observers,
mbelshe@google.com877d2032008-10-23 08:09:21 +090050// we simply call PostTask to each registered thread, and then each thread
51// will notify its regular ObserverList.
52//
53///////////////////////////////////////////////////////////////////////////////
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090054
55// Forward declaration for ObserverListThreadSafeTraits.
56template <class ObserverType>
57class ObserverListThreadSafe;
58
jhawkins@chromium.org4a310212012-01-04 04:36:57 +090059// An UnboundMethod is a wrapper for a method where the actual object is
60// provided at Run dispatch time.
61template <class T, class Method, class Params>
62class UnboundMethod {
63 public:
64 UnboundMethod(Method m, const Params& p) : m_(m), p_(p) {
65 COMPILE_ASSERT(
66 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value),
67 badunboundmethodparams);
68 }
69 void Run(T* obj) const {
70 DispatchToMethod(obj, m_, p_);
71 }
72 private:
73 Method m_;
74 Params p_;
75};
76
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090077// This class is used to work around VS2005 not accepting:
78//
79// friend class
80// base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
81//
82// Instead of friending the class, we could friend the actual function
83// which calls delete. However, this ends up being
84// RefCountedThreadSafe::DeleteInternal(), which is private. So we
85// define our own templated traits class so we can friend it.
86template <class T>
87struct ObserverListThreadSafeTraits {
88 static void Destruct(const ObserverListThreadSafe<T>* x) {
89 delete x;
90 }
91};
92
mbelshe@google.com877d2032008-10-23 08:09:21 +090093template <class ObserverType>
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090094class ObserverListThreadSafe
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090095 : public base::RefCountedThreadSafe<
96 ObserverListThreadSafe<ObserverType>,
97 ObserverListThreadSafeTraits<ObserverType> > {
mbelshe@google.com877d2032008-10-23 08:09:21 +090098 public:
willchan@chromium.org4c7f03e2010-09-01 07:54:21 +090099 typedef typename ObserverList<ObserverType>::NotificationType
100 NotificationType;
101
102 ObserverListThreadSafe()
103 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
104 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
mbelshe@google.com877d2032008-10-23 08:09:21 +0900105
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900106 // Add an observer to the list. An observer should not be added to
107 // the same list more than once.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900108 void AddObserver(ObserverType* obs) {
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900109 // If there is not a current MessageLoop, it is impossible to notify on it,
110 // so do not add the observer.
xhwang@chromium.orgff47fa52013-05-04 22:57:01 +0900111 if (!base::MessageLoop::current())
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900112 return;
113
mbelshe@google.com877d2032008-10-23 08:09:21 +0900114 ObserverList<ObserverType>* list = NULL;
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900115 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
mbelshe@google.com877d2032008-10-23 08:09:21 +0900116 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900117 base::AutoLock lock(list_lock_);
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900118 if (observer_lists_.find(thread_id) == observer_lists_.end())
119 observer_lists_[thread_id] = new ObserverListContext(type_);
120 list = &(observer_lists_[thread_id]->list);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900121 }
122 list->AddObserver(obs);
123 }
124
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900125 // Remove an observer from the list if it is in the list.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900126 // If there are pending notifications in-transit to the observer, they will
127 // be aborted.
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900128 // If the observer to be removed is in the list, RemoveObserver MUST
129 // be called from the same thread which called AddObserver.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900130 void RemoveObserver(ObserverType* obs) {
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900131 ObserverListContext* context = NULL;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900132 ObserverList<ObserverType>* list = NULL;
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900133 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
mbelshe@google.com877d2032008-10-23 08:09:21 +0900134 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900135 base::AutoLock lock(list_lock_);
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900136 typename ObserversListMap::iterator it = observer_lists_.find(thread_id);
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900137 if (it == observer_lists_.end()) {
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900138 // This will happen if we try to remove an observer on a thread
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900139 // we never added an observer for.
mbelshe@google.com2d95cab2008-11-04 02:15:07 +0900140 return;
141 }
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900142 context = it->second;
143 list = &context->list;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900144
145 // If we're about to remove the last observer from the list,
146 // then we can remove this observer_list entirely.
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900147 if (list->HasObserver(obs) && list->size() == 1)
148 observer_lists_.erase(it);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900149 }
150 list->RemoveObserver(obs);
151
152 // If RemoveObserver is called from a notification, the size will be
153 // nonzero. Instead of deleting here, the NotifyWrapper will delete
154 // when it finishes iterating.
155 if (list->size() == 0)
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900156 delete context;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900157 }
158
sergeyu@chromium.org86992ef2012-02-08 09:22:11 +0900159 // Verifies that the list is currently empty (i.e. there are no observers).
160 void AssertEmpty() const {
161 base::AutoLock lock(list_lock_);
162 DCHECK(observer_lists_.empty());
163 }
164
mbelshe@google.com877d2032008-10-23 08:09:21 +0900165 // Notify methods.
166 // Make a thread-safe callback to each Observer in the list.
167 // Note, these calls are effectively asynchronous. You cannot assume
168 // that at the completion of the Notify call that all Observers have
169 // been Notified. The notification may still be pending delivery.
170 template <class Method>
171 void Notify(Method m) {
172 UnboundMethod<ObserverType, Method, Tuple0> method(m, MakeTuple());
173 Notify<Method, Tuple0>(method);
174 }
175
176 template <class Method, class A>
akalin@chromium.org59a0fef2011-06-17 07:32:14 +0900177 void Notify(Method m, const A& a) {
mbelshe@google.com877d2032008-10-23 08:09:21 +0900178 UnboundMethod<ObserverType, Method, Tuple1<A> > method(m, MakeTuple(a));
179 Notify<Method, Tuple1<A> >(method);
180 }
181
akalin@chromium.org59a0fef2011-06-17 07:32:14 +0900182 template <class Method, class A, class B>
183 void Notify(Method m, const A& a, const B& b) {
184 UnboundMethod<ObserverType, Method, Tuple2<A, B> > method(
185 m, MakeTuple(a, b));
186 Notify<Method, Tuple2<A, B> >(method);
187 }
188
189 template <class Method, class A, class B, class C>
190 void Notify(Method m, const A& a, const B& b, const C& c) {
191 UnboundMethod<ObserverType, Method, Tuple3<A, B, C> > method(
192 m, MakeTuple(a, b, c));
193 Notify<Method, Tuple3<A, B, C> >(method);
194 }
195
196 template <class Method, class A, class B, class C, class D>
197 void Notify(Method m, const A& a, const B& b, const C& c, const D& d) {
198 UnboundMethod<ObserverType, Method, Tuple4<A, B, C, D> > method(
199 m, MakeTuple(a, b, c, d));
200 Notify<Method, Tuple4<A, B, C, D> >(method);
201 }
202
mbelshe@google.com877d2032008-10-23 08:09:21 +0900203 // TODO(mbelshe): Add more wrappers for Notify() with more arguments.
204
205 private:
akalin@chromium.orge43be3d2011-01-12 06:19:54 +0900206 // See comment above ObserverListThreadSafeTraits' definition.
207 friend struct ObserverListThreadSafeTraits<ObserverType>;
208
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900209 struct ObserverListContext {
210 explicit ObserverListContext(NotificationType type)
nduca@chromium.orgba048612011-08-16 05:33:46 +0900211 : loop(base::MessageLoopProxy::current()),
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900212 list(type) {
213 }
214
215 scoped_refptr<base::MessageLoopProxy> loop;
216 ObserverList<ObserverType> list;
217
218 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
219 };
220
akalin@chromium.org982d9d52011-01-11 05:40:36 +0900221 ~ObserverListThreadSafe() {
tfarina@chromium.orge2903a52013-03-17 14:52:05 +0900222 STLDeleteValues(&observer_lists_);
akalin@chromium.org982d9d52011-01-11 05:40:36 +0900223 }
224
mbelshe@google.com877d2032008-10-23 08:09:21 +0900225 template <class Method, class Params>
226 void Notify(const UnboundMethod<ObserverType, Method, Params>& method) {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900227 base::AutoLock lock(list_lock_);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900228 typename ObserversListMap::iterator it;
229 for (it = observer_lists_.begin(); it != observer_lists_.end(); ++it) {
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900230 ObserverListContext* context = (*it).second;
231 context->loop->PostTask(
willchan@chromium.orgd52d47f2010-02-13 06:38:37 +0900232 FROM_HERE,
jhawkins@chromium.org22d67562011-10-13 05:26:50 +0900233 base::Bind(&ObserverListThreadSafe<ObserverType>::
234 template NotifyWrapper<Method, Params>, this, context, method));
mbelshe@google.com877d2032008-10-23 08:09:21 +0900235 }
236 }
237
238 // Wrapper which is called to fire the notifications for each thread's
239 // ObserverList. This function MUST be called on the thread which owns
240 // the unsafe ObserverList.
241 template <class Method, class Params>
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900242 void NotifyWrapper(ObserverListContext* context,
mbelshe@google.com877d2032008-10-23 08:09:21 +0900243 const UnboundMethod<ObserverType, Method, Params>& method) {
244
245 // Check that this list still needs notifications.
246 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900247 base::AutoLock lock(list_lock_);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900248 typename ObserversListMap::iterator it =
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900249 observer_lists_.find(base::PlatformThread::CurrentId());
mbelshe@google.com877d2032008-10-23 08:09:21 +0900250
251 // The ObserverList could have been removed already. In fact, it could
252 // have been removed and then re-added! If the master list's loop
253 // does not match this one, then we do not need to finish this
254 // notification.
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900255 if (it == observer_lists_.end() || it->second != context)
mbelshe@google.com877d2032008-10-23 08:09:21 +0900256 return;
257 }
258
259 {
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900260 typename ObserverList<ObserverType>::Iterator it(context->list);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900261 ObserverType* obs;
262 while ((obs = it.GetNext()) != NULL)
263 method.Run(obs);
264 }
265
266 // If there are no more observers on the list, we can now delete it.
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900267 if (context->list.size() == 0) {
mbelshe@google.com877d2032008-10-23 08:09:21 +0900268 {
brettw@chromium.orgabe477a2011-01-21 13:55:52 +0900269 base::AutoLock lock(list_lock_);
willchan@chromium.org2777ca52010-09-18 04:33:06 +0900270 // Remove |list| if it's not already removed.
271 // This can happen if multiple observers got removed in a notification.
272 // See http://crbug.com/55725.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900273 typename ObserversListMap::iterator it =
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900274 observer_lists_.find(base::PlatformThread::CurrentId());
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900275 if (it != observer_lists_.end() && it->second == context)
willchan@chromium.org2777ca52010-09-18 04:33:06 +0900276 observer_lists_.erase(it);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900277 }
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900278 delete context;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900279 }
280 }
281
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900282 // Key by PlatformThreadId because in tests, clients can attempt to remove
283 // observers without a MessageLoop. If this were keyed by MessageLoop, that
284 // operation would be silently ignored, leaving garbage in the ObserverList.
285 typedef std::map<base::PlatformThreadId, ObserverListContext*>
286 ObserversListMap;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900287
sergeyu@chromium.org86992ef2012-02-08 09:22:11 +0900288 mutable base::Lock list_lock_; // Protects the observer_lists_.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900289 ObserversListMap observer_lists_;
willchan@chromium.org4c7f03e2010-09-01 07:54:21 +0900290 const NotificationType type_;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900291
tfarina@chromium.org0aad8422010-06-05 01:13:51 +0900292 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900293};
294
295#endif // BASE_OBSERVER_LIST_THREADSAFE_H_