From 6689c901cb70da01beded7c108dadfcaca34caf4 Mon Sep 17 00:00:00 2001 From: Daniel 2 Olofsson Date: Tue, 4 Feb 2014 14:28:49 +0100 Subject: [PATCH] IndexOutOfBoundsException on addPreference in PreferenceGroup IndexOutOfBoundsException thrown when attempting to add preference to PreferenceGroup and at same time removing all preferences in list. Issue is caused by a race condition in addPreference that retrieves index of where to add Preference from binary search of mPreferenceList outside of synchronized lock. If list is cleared after this point but prior to adding preference on index returned from binarySearch exception is thrown. Solved by moving binarySearch to inside synchronized block. This will allow thread safety while not impacting behavior as result from search is only ever used from within synchronized block. Change-Id: Ic1e7954cf977b1ddd6ddba98d4cf771f21fb4d57 --- core/java/android/preference/PreferenceGroup.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/core/java/android/preference/PreferenceGroup.java b/core/java/android/preference/PreferenceGroup.java index 2d35b1be30865..8065188ad8ca6 100644 --- a/core/java/android/preference/PreferenceGroup.java +++ b/core/java/android/preference/PreferenceGroup.java @@ -151,16 +151,15 @@ public boolean addPreference(Preference preference) { } } - int insertionIndex = Collections.binarySearch(mPreferenceList, preference); - if (insertionIndex < 0) { - insertionIndex = insertionIndex * -1 - 1; - } - if (!onPrepareAddPreference(preference)) { return false; } synchronized(this) { + int insertionIndex = Collections.binarySearch(mPreferenceList, preference); + if (insertionIndex < 0) { + insertionIndex = insertionIndex * -1 - 1; + } mPreferenceList.add(insertionIndex, preference); }