From 6edbf68e84bf56e6d083215e4ed8e3cc32ac48dd Mon Sep 17 00:00:00 2001 From: Daniel Nishi Date: Mon, 1 Apr 2019 13:12:51 -0700 Subject: [PATCH] Explicitly close file stream when initializing quotas. When the device boots and the StorageStatsService is initialized, we load the last calculated cache quotas from a file. We were never closing the FileInputStream and leaked a resource. By using try-with-resources, we can avoid that. Bug: 128920416 Test: Manual -- did not crash on a phone that booted a few times. Change-Id: Ib85e571ddf033caf63eef7c69a91336dad1b55bc --- .../server/storage/CacheQuotaStrategy.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/services/core/java/com/android/server/storage/CacheQuotaStrategy.java b/services/core/java/com/android/server/storage/CacheQuotaStrategy.java index 7a35bf7bba128..2df7370f82961 100644 --- a/services/core/java/com/android/server/storage/CacheQuotaStrategy.java +++ b/services/core/java/com/android/server/storage/CacheQuotaStrategy.java @@ -66,7 +66,6 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import java.util.Map; /** * CacheQuotaStrategy is a strategy for determining cache quotas using usage stats and foreground @@ -296,26 +295,24 @@ public class CacheQuotaStrategy implements RemoteCallback.OnResultListener { * @return the number of bytes that were free on the device when the quotas were last calced. */ public long setupQuotasFromFile() throws IOException { - FileInputStream stream; - try { - stream = mPreviousValuesFile.openRead(); + Pair> cachedValues = null; + try (FileInputStream stream = mPreviousValuesFile.openRead()) { + try { + cachedValues = readFromXml(stream); + } catch (XmlPullParserException e) { + throw new IllegalStateException(e.getMessage()); + } } catch (FileNotFoundException e) { // The file may not exist yet -- this isn't truly exceptional. return -1; } - Pair> cachedValues = null; - try { - cachedValues = readFromXml(stream); - } catch (XmlPullParserException e) { - throw new IllegalStateException(e.getMessage()); - } - if (cachedValues == null) { Slog.e(TAG, "An error occurred while parsing the cache quota file."); return -1; } pushProcessedQuotas(cachedValues.second); + return cachedValues.first; }