diff --git a/src/com/android/launcher3/model/DatabaseHelper.java b/src/com/android/launcher3/model/DatabaseHelper.java index 8368256164..ed4f492a80 100644 --- a/src/com/android/launcher3/model/DatabaseHelper.java +++ b/src/com/android/launcher3/model/DatabaseHelper.java @@ -56,6 +56,7 @@ import java.io.File; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.ToLongFunction; import java.util.stream.Collectors; @@ -79,8 +80,8 @@ public class DatabaseHelper extends NoLocaleSQLiteHelper implements private final Context mContext; private final ToLongFunction mUserSerialProvider; private final Runnable mOnEmptyDbCreateCallback; + private final AtomicInteger mMaxItemId = new AtomicInteger(-1); - private int mMaxItemId = -1; public boolean mHotseatRestoreTableExists; /** @@ -97,21 +98,19 @@ public class DatabaseHelper extends NoLocaleSQLiteHelper implements protected void initIds() { // In the case where neither onCreate nor onUpgrade gets called, we read the maxId from // the DB here - if (mMaxItemId == -1) { - mMaxItemId = initializeMaxItemId(getWritableDatabase()); - } + mMaxItemId.compareAndSet(-1, initializeMaxItemId(getWritableDatabase())); } @Override public void onCreate(SQLiteDatabase db) { if (LOGD) Log.d(TAG, "creating new launcher database"); - mMaxItemId = 1; + mMaxItemId.set(1); addTableToDb(db, getDefaultUserSerial(), false /* optional */); // Fresh and clean launcher DB. - mMaxItemId = initializeMaxItemId(db); + mMaxItemId.set(initializeMaxItemId(db)); mOnEmptyDbCreateCallback.run(); } @@ -451,11 +450,10 @@ public class DatabaseHelper extends NoLocaleSQLiteHelper implements // after that point @Override public int generateNewItemId() { - if (mMaxItemId < 0) { + if (mMaxItemId.get() < 0) { throw new RuntimeException("Error: max item id was not initialized"); } - mMaxItemId += 1; - return mMaxItemId; + return mMaxItemId.incrementAndGet(); } /** @@ -484,7 +482,7 @@ public class DatabaseHelper extends NoLocaleSQLiteHelper implements public void checkId(ContentValues values) { int id = values.getAsInteger(Favorites._ID); - mMaxItemId = Math.max(id, mMaxItemId); + mMaxItemId.accumulateAndGet(id, Math::max); } private int initializeMaxItemId(SQLiteDatabase db) { @@ -508,7 +506,7 @@ public class DatabaseHelper extends NoLocaleSQLiteHelper implements int count = loader.loadLayout(db); // Ensure that the max ids are initialized - mMaxItemId = initializeMaxItemId(db); + mMaxItemId.set(initializeMaxItemId(db)); return count; }