1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.messaging.datamodel; 18 19 import com.android.messaging.Factory; 20 21 import java.util.HashSet; 22 23 /** 24 * Utility abstraction which allows MemoryCaches in an application to register and then when there 25 * is memory pressure provide a callback to reclaim the memory in the caches. 26 */ 27 public class MemoryCacheManager { 28 private final HashSet<MemoryCache> mMemoryCaches = new HashSet<MemoryCache>(); 29 private final Object mMemoryCacheLock = new Object(); 30 get()31 public static MemoryCacheManager get() { 32 return Factory.get().getMemoryCacheManager(); 33 } 34 35 /** 36 * Extend this interface to provide a reclaim method on a memory cache. 37 */ 38 public interface MemoryCache { reclaim()39 void reclaim(); 40 } 41 42 /** 43 * Register the memory cache with the application. 44 */ registerMemoryCache(final MemoryCache cache)45 public void registerMemoryCache(final MemoryCache cache) { 46 synchronized (mMemoryCacheLock) { 47 mMemoryCaches.add(cache); 48 } 49 } 50 51 /** 52 * Unregister the memory cache with the application. 53 */ unregisterMemoryCache(final MemoryCache cache)54 public void unregisterMemoryCache(final MemoryCache cache) { 55 synchronized (mMemoryCacheLock) { 56 mMemoryCaches.remove(cache); 57 } 58 } 59 60 /** 61 * Reclaim memory in all the memory caches in the application. 62 */ 63 @SuppressWarnings("unchecked") reclaimMemory()64 public void reclaimMemory() { 65 // We're creating a cache copy in the lock to ensure we're not working on a concurrently 66 // modified set, then reclaim outside of the lock to minimize the time within the lock. 67 final HashSet<MemoryCache> shallowCopy; 68 synchronized (mMemoryCacheLock) { 69 shallowCopy = (HashSet<MemoryCache>) mMemoryCaches.clone(); 70 } 71 for (final MemoryCache cache : shallowCopy) { 72 cache.reclaim(); 73 } 74 } 75 } 76