Fix issue #17811029: Settings provider race when removing users

Change-Id: Ia40d0a9c161b765d1340db5390d0acdbfc050b81
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 3453a67..34e57bc 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -506,7 +506,14 @@
     }
 
     private void fullyPopulateCaches(final int userHandle) {
-        DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
+        DatabaseHelper dbHelper;
+        synchronized (this) {
+            dbHelper = mOpenHelpers.get(userHandle);
+        }
+        if (dbHelper == null) {
+            // User is gone.
+            return;
+        }
         // Only populate the globals cache once, for the owning user
         if (userHandle == UserHandle.USER_OWNER) {
             fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
@@ -611,10 +618,15 @@
 
         long oldId = Binder.clearCallingIdentity();
         try {
-            DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
+            DatabaseHelper dbHelper;
+            synchronized (this) {
+                dbHelper = mOpenHelpers.get(callingUser);
+            }
             if (null == dbHelper) {
                 establishDbTracking(callingUser);
-                dbHelper = mOpenHelpers.get(callingUser);
+                synchronized (this) {
+                    dbHelper = mOpenHelpers.get(callingUser);
+                }
             }
             return dbHelper;
         } finally {