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// MemoryPressure provides static APIs for handling memory pressure on
6// platforms that have such signals, such as Android.
7// The app will try to discard buffers that aren't deemed essential (individual
8// modules will implement their own policy).
9//
10// Refer to memory_pressure_level_list.h for information about what sorts of
11// signals can be sent under what conditions.
12
13#ifndef BASE_MEMORY_PRESSURE_LISTENER_H_
14#define BASE_MEMORY_PRESSURE_LISTENER_H_
15
16#include "base/base_export.h"
17#include "base/basictypes.h"
18#include "base/callback.h"
19
20namespace base {
21
22// To start listening, create a new instance, passing a callback to a
23// function that takes a MemoryPressureLevel parameter. To stop listening,
24// simply delete the listener object. The implementation guarantees
25// that the callback will always be called on the thread that created
26// the listener.
27// Note that even on the same thread, the callback is not guaranteed to be
28// called synchronously within the system memory pressure broadcast.
29// Please see notes on memory_pressure_level_list.h: some levels are absolutely
30// critical, and if not enough memory is returned to the system, it'll
31// potentially kill the app, and then later the app will have to be
32// cold-started.
33//
34//
35// Example:
36//
37//    void OnMemoryPressure(MemoryPressureLevel memory_pressure_level) {
38//       ...
39//    }
40//
41//    // Start listening.
42//    MemoryPressureListener* my_listener =
43//        new MemoryPressureListener(base::Bind(&OnMemoryPressure));
44//
45//    ...
46//
47//    // Stop listening.
48//    delete my_listener;
49//
50class BASE_EXPORT MemoryPressureListener {
51 public:
52  enum MemoryPressureLevel {
53#define DEFINE_MEMORY_PRESSURE_LEVEL(name, value) name = value,
54#include "base/memory/memory_pressure_level_list.h"
55#undef DEFINE_MEMORY_PRESSURE_LEVEL
56  };
57
58  typedef base::Callback<void(MemoryPressureLevel)> MemoryPressureCallback;
59
60  explicit MemoryPressureListener(
61      const MemoryPressureCallback& memory_pressure_callback);
62  ~MemoryPressureListener();
63
64  // Intended for use by the platform specific implementation.
65  static void NotifyMemoryPressure(MemoryPressureLevel memory_pressure_level);
66
67 private:
68  void Notify(MemoryPressureLevel memory_pressure_level);
69
70  MemoryPressureCallback callback_;
71
72  DISALLOW_COPY_AND_ASSIGN(MemoryPressureListener);
73};
74
75}  // namespace base
76
77#endif  // BASE_MEMORY_PRESSURE_LISTENER_H_
78