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.
5 #include "base/memory/discardable_memory_emulated.h"
7 #include "base/lazy_instance.h"
8 #include "base/memory/discardable_memory_manager.h"
13 // This is admittedly pretty magical.
14 const size_t kEmulatedMemoryLimit
= 512 * 1024 * 1024;
15 const size_t kEmulatedSoftMemoryLimit
= 32 * 1024 * 1024;
16 const size_t kEmulatedHardMemoryLimitExpirationTimeMs
= 1000;
18 // internal::DiscardableMemoryManager has an explicit constructor that takes
19 // a number of memory limit parameters. The LeakyLazyInstanceTraits doesn't
20 // handle the case. Thus, we need our own class here.
21 struct DiscardableMemoryManagerLazyInstanceTraits
{
22 // Leaky as discardable memory clients can use this after the exit handler
24 static const bool kRegisterOnExit
= false;
26 static const bool kAllowedToAccessOnNonjoinableThread
= true;
29 static internal::DiscardableMemoryManager
* New(void* instance
) {
30 return new (instance
) internal::DiscardableMemoryManager(
32 kEmulatedSoftMemoryLimit
,
33 TimeDelta::FromMilliseconds(kEmulatedHardMemoryLimitExpirationTimeMs
));
35 static void Delete(internal::DiscardableMemoryManager
* instance
) {
36 instance
->~DiscardableMemoryManager();
40 LazyInstance
<internal::DiscardableMemoryManager
,
41 DiscardableMemoryManagerLazyInstanceTraits
>
42 g_manager
= LAZY_INSTANCE_INITIALIZER
;
48 DiscardableMemoryEmulated::DiscardableMemoryEmulated(size_t bytes
)
51 g_manager
.Pointer()->Register(this, bytes
);
54 DiscardableMemoryEmulated::~DiscardableMemoryEmulated() {
57 g_manager
.Pointer()->Unregister(this);
61 bool DiscardableMemoryEmulated::ReduceMemoryUsage() {
62 return g_manager
.Pointer()->ReduceMemoryUsage();
66 void DiscardableMemoryEmulated::ReduceMemoryUsageUntilWithinLimit(
68 g_manager
.Pointer()->ReduceMemoryUsageUntilWithinLimit(bytes
);
71 bool DiscardableMemoryEmulated::Initialize() {
72 return Lock() != DISCARDABLE_MEMORY_LOCK_STATUS_FAILED
;
75 DiscardableMemoryLockStatus
DiscardableMemoryEmulated::Lock() {
79 if (!g_manager
.Pointer()->AcquireLock(this, &purged
))
80 return DISCARDABLE_MEMORY_LOCK_STATUS_FAILED
;
83 return purged
? DISCARDABLE_MEMORY_LOCK_STATUS_PURGED
84 : DISCARDABLE_MEMORY_LOCK_STATUS_SUCCESS
;
87 void DiscardableMemoryEmulated::Unlock() {
89 g_manager
.Pointer()->ReleaseLock(this);
93 void* DiscardableMemoryEmulated::Memory() const {
99 bool DiscardableMemoryEmulated::AllocateAndAcquireLock() {
103 memory_
.reset(new uint8
[bytes_
]);
107 void DiscardableMemoryEmulated::Purge() {
111 } // namespace internal