Revert of Added EventSender.setTouchPointRadius() for layoutTests (patchset #4 id...
[chromium-blink-merge.git] / base / observer_list_threadsafe.h
blob46ce88066931150c0bce56de59c5b9d7f373f9c6
1 // Copyright (c) 2012 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.
5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
6 #define BASE_OBSERVER_LIST_THREADSAFE_H_
8 #include <algorithm>
9 #include <map>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/location.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/observer_list.h"
19 #include "base/stl_util.h"
20 #include "base/threading/platform_thread.h"
22 ///////////////////////////////////////////////////////////////////////////////
24 // OVERVIEW:
26 // A thread-safe container for a list of observers.
27 // This is similar to the observer_list (see observer_list.h), but it
28 // is more robust for multi-threaded situations.
30 // 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.
34 // * Any thread may trigger a notification via Notify().
35 // * 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.
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.
47 // IMPLEMENTATION NOTES
48 // The ObserverListThreadSafe maintains an ObserverList for each thread
49 // which uses the ThreadSafeObserver. When Notifying the observers,
50 // we simply call PostTask to each registered thread, and then each thread
51 // will notify its regular ObserverList.
53 ///////////////////////////////////////////////////////////////////////////////
55 // Forward declaration for ObserverListThreadSafeTraits.
56 template <class ObserverType>
57 class ObserverListThreadSafe;
59 // An UnboundMethod is a wrapper for a method where the actual object is
60 // provided at Run dispatch time.
61 template <class T, class Method, class Params>
62 class 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);
69 void Run(T* obj) const {
70 DispatchToMethod(obj, m_, p_);
72 private:
73 Method m_;
74 Params p_;
77 // This class is used to work around VS2005 not accepting:
79 // friend class
80 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
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.
86 template <class T>
87 struct ObserverListThreadSafeTraits {
88 static void Destruct(const ObserverListThreadSafe<T>* x) {
89 delete x;
93 template <class ObserverType>
94 class ObserverListThreadSafe
95 : public base::RefCountedThreadSafe<
96 ObserverListThreadSafe<ObserverType>,
97 ObserverListThreadSafeTraits<ObserverType> > {
98 public:
99 typedef typename ObserverList<ObserverType>::NotificationType
100 NotificationType;
102 ObserverListThreadSafe()
103 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
104 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
106 // Add an observer to the list. An observer should not be added to
107 // the same list more than once.
108 void AddObserver(ObserverType* obs) {
109 // If there is not a current MessageLoop, it is impossible to notify on it,
110 // so do not add the observer.
111 if (!base::MessageLoop::current())
112 return;
114 ObserverList<ObserverType>* list = NULL;
115 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
117 base::AutoLock lock(list_lock_);
118 if (observer_lists_.find(thread_id) == observer_lists_.end())
119 observer_lists_[thread_id] = new ObserverListContext(type_);
120 list = &(observer_lists_[thread_id]->list);
122 list->AddObserver(obs);
125 // Remove an observer from the list if it is in the list.
126 // If there are pending notifications in-transit to the observer, they will
127 // be aborted.
128 // If the observer to be removed is in the list, RemoveObserver MUST
129 // be called from the same thread which called AddObserver.
130 void RemoveObserver(ObserverType* obs) {
131 ObserverListContext* context = NULL;
132 ObserverList<ObserverType>* list = NULL;
133 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId();
135 base::AutoLock lock(list_lock_);
136 typename ObserversListMap::iterator it = observer_lists_.find(thread_id);
137 if (it == observer_lists_.end()) {
138 // This will happen if we try to remove an observer on a thread
139 // we never added an observer for.
140 return;
142 context = it->second;
143 list = &context->list;
145 // If we're about to remove the last observer from the list,
146 // then we can remove this observer_list entirely.
147 if (list->HasObserver(obs) && list->size() == 1)
148 observer_lists_.erase(it);
150 list->RemoveObserver(obs);
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)
156 delete context;
159 // 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());
165 // 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, class... Params>
171 void Notify(const tracked_objects::Location& from_here,
172 Method m,
173 const Params&... params) {
174 UnboundMethod<ObserverType, Method, Tuple<Params...>> method(
175 m, MakeTuple(params...));
177 base::AutoLock lock(list_lock_);
178 for (const auto& entry : observer_lists_) {
179 ObserverListContext* context = entry.second;
180 context->loop->PostTask(
181 from_here,
182 base::Bind(
183 &ObserverListThreadSafe<ObserverType>::template NotifyWrapper<
184 Method, Tuple<Params...>>,
185 this, context, method));
189 private:
190 // See comment above ObserverListThreadSafeTraits' definition.
191 friend struct ObserverListThreadSafeTraits<ObserverType>;
193 struct ObserverListContext {
194 explicit ObserverListContext(NotificationType type)
195 : loop(base::MessageLoopProxy::current()),
196 list(type) {
199 scoped_refptr<base::MessageLoopProxy> loop;
200 ObserverList<ObserverType> list;
202 private:
203 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
206 ~ObserverListThreadSafe() {
207 STLDeleteValues(&observer_lists_);
210 // Wrapper which is called to fire the notifications for each thread's
211 // ObserverList. This function MUST be called on the thread which owns
212 // the unsafe ObserverList.
213 template <class Method, class Params>
214 void NotifyWrapper(ObserverListContext* context,
215 const UnboundMethod<ObserverType, Method, Params>& method) {
216 // Check that this list still needs notifications.
218 base::AutoLock lock(list_lock_);
219 typename ObserversListMap::iterator it =
220 observer_lists_.find(base::PlatformThread::CurrentId());
222 // The ObserverList could have been removed already. In fact, it could
223 // have been removed and then re-added! If the master list's loop
224 // does not match this one, then we do not need to finish this
225 // notification.
226 if (it == observer_lists_.end() || it->second != context)
227 return;
231 typename ObserverList<ObserverType>::Iterator it(&context->list);
232 ObserverType* obs;
233 while ((obs = it.GetNext()) != NULL)
234 method.Run(obs);
237 // If there are no more observers on the list, we can now delete it.
238 if (context->list.size() == 0) {
240 base::AutoLock lock(list_lock_);
241 // Remove |list| if it's not already removed.
242 // This can happen if multiple observers got removed in a notification.
243 // See http://crbug.com/55725.
244 typename ObserversListMap::iterator it =
245 observer_lists_.find(base::PlatformThread::CurrentId());
246 if (it != observer_lists_.end() && it->second == context)
247 observer_lists_.erase(it);
249 delete context;
253 // Key by PlatformThreadId because in tests, clients can attempt to remove
254 // observers without a MessageLoop. If this were keyed by MessageLoop, that
255 // operation would be silently ignored, leaving garbage in the ObserverList.
256 typedef std::map<base::PlatformThreadId, ObserverListContext*>
257 ObserversListMap;
259 mutable base::Lock list_lock_; // Protects the observer_lists_.
260 ObserversListMap observer_lists_;
261 const NotificationType type_;
263 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
266 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_