1 // Copyright 2013 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. 4 5 #include "base/memory/memory_pressure_listener.h" 6 7 #include "base/debug/trace_event.h" 8 #include "base/lazy_instance.h" 9 #include "base/observer_list_threadsafe.h" 10 11 namespace { 12 13 // ObserverListThreadSafe is RefCountedThreadSafe, this traits is needed 14 // to ensure the LazyInstance will hold a reference to it. 15 struct LeakyLazyObserverListTraits : 16 base::internal::LeakyLazyInstanceTraits< 17 ObserverListThreadSafe<base::MemoryPressureListener> > { 18 static ObserverListThreadSafe<base::MemoryPressureListener>* 19 New(void* instance) { 20 ObserverListThreadSafe<base::MemoryPressureListener>* ret = 21 base::internal::LeakyLazyInstanceTraits< 22 ObserverListThreadSafe<base::MemoryPressureListener> >::New( 23 instance); 24 // Leaky. 25 ret->AddRef(); 26 return ret; 27 } 28 }; 29 30 base::LazyInstance< 31 ObserverListThreadSafe<base::MemoryPressureListener>, 32 LeakyLazyObserverListTraits> g_observers = LAZY_INSTANCE_INITIALIZER; 33 } // namespace 34 35 namespace base { 36 37 MemoryPressureListener::MemoryPressureListener( 38 const MemoryPressureListener::MemoryPressureCallback& callback) 39 : callback_(callback) { 40 g_observers.Get().AddObserver(this); 41 } 42 43 MemoryPressureListener::~MemoryPressureListener() { 44 g_observers.Get().RemoveObserver(this); 45 } 46 47 void MemoryPressureListener::Notify(MemoryPressureLevel memory_pressure_level) { 48 callback_.Run(memory_pressure_level); 49 } 50 51 // static 52 void MemoryPressureListener::NotifyMemoryPressure( 53 MemoryPressureLevel memory_pressure_level) { 54 TRACE_EVENT1("memory", "MemoryPressureListener::NotifyMemoryPressure", 55 "level", memory_pressure_level); 56 g_observers.Get().Notify(&MemoryPressureListener::Notify, 57 memory_pressure_level); 58 } 59 60 } // namespace base 61