Merge "Fix concurrency issue in PropertyInvalidatedCache" into tm-qpr-dev

This commit is contained in:
Lee Shombert
2023-01-17 20:05:23 +00:00
committed by Android (Google) Code Review
2 changed files with 33 additions and 2 deletions

View File

@@ -1405,6 +1405,17 @@ public class PropertyInvalidatedCache<Query, Result> {
return isDisabled(); return isDisabled();
} }
/**
* Return the number of entries in the cache. This is used for testing and has package-only
* visibility.
* @hide
*/
public int size() {
synchronized (mLock) {
return mCache.size();
}
}
/** /**
* Returns a list of caches alive at the current time. * Returns a list of caches alive at the current time.
*/ */
@@ -1612,8 +1623,12 @@ public class PropertyInvalidatedCache<Query, Result> {
* @hide * @hide
*/ */
public static void onTrimMemory() { public static void onTrimMemory() {
for (PropertyInvalidatedCache pic : getActiveCaches()) { ArrayList<PropertyInvalidatedCache> activeCaches;
pic.clear(); synchronized (sGlobalLock) {
activeCaches = getActiveCaches();
}
for (int i = 0; i < activeCaches.size(); i++) {
activeCaches.get(i).clear();
} }
} }
} }

View File

@@ -368,4 +368,20 @@ public class PropertyInvalidatedCacheTests {
PropertyInvalidatedCache.MODULE_BLUETOOTH, "getState"); PropertyInvalidatedCache.MODULE_BLUETOOTH, "getState");
assertEquals(n1, "cache_key.bluetooth.get_state"); assertEquals(n1, "cache_key.bluetooth.get_state");
} }
@Test
public void testOnTrimMemory() {
TestCache cache = new TestCache(MODULE, "trimMemoryTest");
// The cache is not active until it has been invalidated once.
cache.invalidateCache();
// Populate the cache with six entries.
for (int i = 0; i < 6; i++) {
cache.query(i);
}
// The maximum number of entries in TestCache is 4, so even though six entries were
// created, only four are retained.
assertEquals(4, cache.size());
PropertyInvalidatedCache.onTrimMemory();
assertEquals(0, cache.size());
}
} }