1 // Copyright (c) 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.
5 #ifndef BASE_MEMORY_DISCARDABLE_MEMORY_H_
6 #define BASE_MEMORY_DISCARDABLE_MEMORY_H_
11 #include "base/base_export.h"
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/memory/scoped_ptr.h"
18 // Platform abstraction for discardable memory. DiscardableMemory is used to
19 // cache large objects without worrying about blowing out memory, both on mobile
20 // devices where there is no swap, and desktop devices where unused free memory
21 // should be used to help the user experience. This is preferable to releasing
22 // memory in response to an OOM signal because it is simpler, though it has less
23 // flexibility as to which objects get discarded.
25 // Discardable memory has two states: locked and unlocked. While the memory is
26 // locked, it will not be discarded. Unlocking the memory allows the OS to
27 // reclaim it if needed. Locks do not nest.
30 // - The paging behavior of memory while it is locked is not specified. While
31 // mobile platforms will not swap it out, it may qualify for swapping
32 // on desktop platforms. It is not expected that this will matter, as the
33 // preferred pattern of usage for DiscardableMemory is to lock down the
34 // memory, use it as quickly as possible, and then unlock it.
35 // - Because of memory alignment, the amount of memory allocated can be
36 // larger than the requested memory size. It is not very efficient for
38 // - A discardable memory instance is not thread safe. It is the
39 // responsibility of users of discardable memory to ensure there are no
43 // - Linux: http://lwn.net/Articles/452035/
44 // - Mac: http://trac.webkit.org/browser/trunk/Source/WebCore/platform/mac/PurgeableBufferMac.cpp
45 // the comment starting with "vm_object_purgable_control" at
46 // http://www.opensource.apple.com/source/xnu/xnu-792.13.8/osfmk/vm/vm_object.c
48 // Thread-safety: DiscardableMemory instances are not thread-safe.
49 class BASE_EXPORT DiscardableMemory
{
51 virtual ~DiscardableMemory() {}
53 // Create a DiscardableMemory instance with |size|.
54 static scoped_ptr
<DiscardableMemory
> CreateLockedMemory(size_t size
);
56 // Locks the memory so that it will not be purged by the system. Returns
57 // true on success. If the return value is false then this object should be
58 // discarded and a new one should be created.
59 virtual bool Lock() WARN_UNUSED_RESULT
= 0;
61 // Unlocks the memory so that it can be purged by the system. Must be called
62 // after every successful lock call.
63 virtual void Unlock() = 0;
65 // Returns the memory address held by this object. The object must be locked
66 // before calling this. Otherwise, this will cause a DCHECK error.
67 virtual void* Memory() const = 0;
72 #endif // BASE_MEMORY_DISCARDABLE_MEMORY_H_