Thursday, October 20, 2011

Database is locked

今天在修理別人的程式碼,
遇到一個錯誤︰
CREATE TABLE android_metadata failed
Failed to setLocale() when constructing, closing the database
android.database.sqlite.SQLiteException: database is locked

查了很多人的討論,
原因很多種,
但是對我現在的案子的原因是︰
兩個執行緒同時做了以下這件事

  if(mDatabaseHelper == null || mSQLiteDatabase == null) {
   DatabaseHelper mDatabaseHelper = new DatabaseHelper(mContext);
   mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
}
 

主要原因是同時間getWritableDatabase()
這樣的行為會導致 database is locked的錯誤。

Solution︰
在這段程式碼外圍加上synchronized,
讓執行緒能排隊執行,
避免2個執行緒同時都將mDatabaseHelper和 mSQLiteDatabase判斷成null而進入執行程式。

註︰Thread的運用真的要很小心!

No comments: