Autofill: improve handling of nameless, ID-less inputs.
[chromium-blink-merge.git] / base / observer_list_threadsafe.h
blobb951a7176c64e4a83802cf62945842aae9bc6fa0
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(Method m, const Params&... params) {
172 UnboundMethod<ObserverType, Method, Tuple<Params...>> method(
173 m, MakeTuple(params...));
175 base::AutoLock lock(list_lock_);
176 for (const auto& entry : observer_lists_) {
177 ObserverListContext* context = entry.second;
178 context->loop->PostTask(
179 FROM_HERE,
180 base::Bind(
181 &ObserverListThreadSafe<ObserverType>::template NotifyWrapper<
182 Method, Tuple<Params...>>,
183 this, context, method));
187 private:
188 // See comment above ObserverListThreadSafeTraits' definition.
189 friend struct ObserverListThreadSafeTraits<ObserverType>;
191 struct ObserverListContext {
192 explicit ObserverListContext(NotificationType type)
193 : loop(base::MessageLoopProxy::current()),
194 list(type) {
197 scoped_refptr<base::MessageLoopProxy> loop;
198 ObserverList<ObserverType> list;
200 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
203 ~ObserverListThreadSafe() {
204 STLDeleteValues(&observer_lists_);
207 // Wrapper which is called to fire the notifications for each thread's
208 // ObserverList. This function MUST be called on the thread which owns
209 // the unsafe ObserverList.
210 template <class Method, class Params>
211 void NotifyWrapper(ObserverListContext* context,
212 const UnboundMethod<ObserverType, Method, Params>& method) {
214 // Check that this list still needs notifications.
216 base::AutoLock lock(list_lock_);
217 typename ObserversListMap::iterator it =
218 observer_lists_.find(base::PlatformThread::CurrentId());
220 // The ObserverList could have been removed already. In fact, it could
221 // have been removed and then re-added! If the master list's loop
222 // does not match this one, then we do not need to finish this
223 // notification.
224 if (it == observer_lists_.end() || it->second != context)
225 return;
229 typename ObserverList<ObserverType>::Iterator it(context->list);
230 ObserverType* obs;
231 while ((obs = it.GetNext()) != NULL)
232 method.Run(obs);
235 // If there are no more observers on the list, we can now delete it.
236 if (context->list.size() == 0) {
238 base::AutoLock lock(list_lock_);
239 // Remove |list| if it's not already removed.
240 // This can happen if multiple observers got removed in a notification.
241 // See http://crbug.com/55725.
242 typename ObserversListMap::iterator it =
243 observer_lists_.find(base::PlatformThread::CurrentId());
244 if (it != observer_lists_.end() && it->second == context)
245 observer_lists_.erase(it);
247 delete context;
251 // Key by PlatformThreadId because in tests, clients can attempt to remove
252 // observers without a MessageLoop. If this were keyed by MessageLoop, that
253 // operation would be silently ignored, leaving garbage in the ObserverList.
254 typedef std::map<base::PlatformThreadId, ObserverListContext*>
255 ObserversListMap;
257 mutable base::Lock list_lock_; // Protects the observer_lists_.
258 ObserversListMap observer_lists_;
259 const NotificationType type_;
261 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
264 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_