我有一个程序的两个部分(实际的应用程序和一个 BroadcastReceiver),它们可能会尝试连接和修改 SQLite 数据库和 SharedPreferences 文件。
1) 我知道您可以与单个 SQLite 数据库建立多个连接。我还读到 SQLite 在尝试修改或读取数据库(UPDATE、INSERT 等)时可以“锁定”数据库,所以我如何正确处理 2 个线程尝试修改/读取单个 SQLite 数据库的情况同时?
现在,我的数据库连接代码/类中有这个代码片段:
private SQLiteDatabase myDatabase;
public boolean insert(ContentValues columnValueMap) throws Exception
{
long result = 0;
int attempt =0;
do
{
if(!myDatabase.isDbLockedByOtherThreads() && !myDatabase.isDbLockedByCurrentThread())
{
synchronized (myDatabase)
{
result=myDatabase.insertOrThrow(TABLE_NAME, TEXT, columnValueMap);
if(result ==0 || result == -1)
{
return false;
}
return true;
}
}
else
{
Thread.sleep(50);
}
attempt++;
}while(attempt<=5);
throw new Exception("Database Locked!");
}
2)我是否还必须担心同时访问 SharedPreferences 文件(哪个线程首先获得访问权限并不重要,我只是担心会引发错误)?
谢谢。
[编辑]提议的改变
public boolean insert(ContentValues columnValueMap) throws Exception
{
long result = 0;
synchronized (myDatabase)
{
result=myDatabase.insertOrThrow(TABLE_NAME, SMS_TEXT, columnValueMap);
if(result ==0 || result == -1)
{
return false;
}
return true;
}
}