From 96db26032e87c0b5c0f150c1a8541baaad2ea9bb Mon Sep 17 00:00:00 2001 From: Svet Ganov Date: Fri, 19 Feb 2016 09:05:04 -0800 Subject: [PATCH] Don't hold a lock while reading shared preferences from disk. Shared prefrences loads thir content from disk on a separate thread to improve performance, however it holds the lock the whole time while reading from disk which as a result blocks operations that don't rely on reading data from being performed intil load completes, e.g. reguistering a prefernces change listener does not depend on having the data loaded. bug:5254577 Change-Id: I5ad67b285631c34d5aadac7138ba8bfaa728cf94 --- .../android/app/SharedPreferencesImpl.java | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/core/java/android/app/SharedPreferencesImpl.java b/core/java/android/app/SharedPreferencesImpl.java index c552cfc986774..c1180e25a0d37 100644 --- a/core/java/android/app/SharedPreferencesImpl.java +++ b/core/java/android/app/SharedPreferencesImpl.java @@ -87,20 +87,20 @@ final class SharedPreferencesImpl implements SharedPreferences { } new Thread("SharedPreferencesImpl-load") { public void run() { - synchronized (SharedPreferencesImpl.this) { - loadFromDiskLocked(); - } + loadFromDisk(); } }.start(); } - private void loadFromDiskLocked() { - if (mLoaded) { - return; - } - if (mBackupFile.exists()) { - mFile.delete(); - mBackupFile.renameTo(mFile); + private void loadFromDisk() { + synchronized (SharedPreferencesImpl.this) { + if (mLoaded) { + return; + } + if (mBackupFile.exists()) { + mFile.delete(); + mBackupFile.renameTo(mFile); + } } // Debugging @@ -118,27 +118,27 @@ final class SharedPreferencesImpl implements SharedPreferences { str = new BufferedInputStream( new FileInputStream(mFile), 16*1024); map = XmlUtils.readMapXml(str); - } catch (XmlPullParserException e) { - Log.w(TAG, "getSharedPreferences", e); - } catch (FileNotFoundException e) { - Log.w(TAG, "getSharedPreferences", e); - } catch (IOException e) { + } catch (XmlPullParserException | IOException e) { Log.w(TAG, "getSharedPreferences", e); } finally { IoUtils.closeQuietly(str); } } } catch (ErrnoException e) { + /* ignore */ } - mLoaded = true; - if (map != null) { - mMap = map; - mStatTimestamp = stat.st_mtime; - mStatSize = stat.st_size; - } else { - mMap = new HashMap(); + + synchronized (SharedPreferencesImpl.this) { + mLoaded = true; + if (map != null) { + mMap = map; + mStatTimestamp = stat.st_mtime; + mStatSize = stat.st_size; + } else { + mMap = new HashMap<>(); + } + notifyAll(); } - notifyAll(); } static File makeBackupFile(File prefsFile) {