我已经用单例模式实现了SQliteOpenHelper,到目前为止它运行得很好。但请考虑以下顺序:
该服务将处理稍后回滚的未提交数据。因此,单例模式加上服务似乎会导致数据隔离问题。然而,我读过许多建议单身人士的帖子。在使用单例时,如何处理此场景?
public class MyApplication extends Application{
private static MyApplication instance;
public MyApplication(){
instance = this;
}
public static Context getContext(){
return instance;
}
}
public class LocalDBHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDB";
private static final String LOG_TAG = "LocalDBHelper";
private static LocalDBHelper instance = null;
/*private constructor to avoid direct instantiation by other classes*/
private LocalDBHelper(){
super(MyApplication.getContext(), DATABASE_NAME, null, DATABASE_VERSION);
}
/*synchronized method to ensure only 1 instance of LocalDBHelper exists*/
public static synchronized LocalDBHelper getInstance(){
if(instance == null){
instance = new LocalDBHelper();
}
return instance;
}
...
...
}事务的使用:
SQLiteDatabase db = LocalDBHelper.getInstance().getWritableDatabase();
db.beginTransaction();
try{
....
...
db.setTransactionSuccessful();
}catch(Exception e){
e.printStackTrace();
}
finally{
db.endTransaction();
}发布于 2014-11-04 12:48:44
SQliteDatabase连接。该系统设计为允许每个线程访问池中的唯一连接。如果没有可用的连接,则另一个线程将等待一个连接。如果它必须等待足够长的时间,你会看到一个类似我在手机下面看到的逻辑警告。因此,单例模式补充了SQLite的线程安全。
W/SQLiteConnectionPool(12695): The connection pool for database 'xyz' has been unable to grant a connection to thread 6386 (AsyncTask #2) with flags 0x1 for 4.0 seconds. W/SQLiteConnectionPool(12695): Connections: 0 active, 1 idle, 0 available.结论:使用单例读取未提交数据的唯一方法是,如果您在同一个线程上,并且在事务结束之前。
https://stackoverflow.com/questions/26731217
复制相似问题