将SQLiteOpenHelper类做成单例会使它成为线程安全的吗? [英] Will making a SQLiteOpenHelper class a singleton make it Thread safe?
问题描述
我正在创建一个包含三个线程的服务:
I am creating a Service in which there are three Threads :
- GPS位置跟踪器,它将位置值写入数据库.
- 同时读取和写入数据库的发件人线程.
- 也可以读写数据库的接收器线程.
现在我已经看到诸如这些之类的帖子.据说其中只有一个Helper类以及数据库连接才可用.我试图通过使用Singleton模式仅实现Helper类的一个实例,但是我对于如何仅创建一个数据库连接来实现前面提到的三个任务感到困惑.这是我对Helper类的实现.
Now I have seen posts like these in which it is said that only one Helper class should be available as well as only on DB connection. I have tried to implement only one instance of the Helper class by using the Singleton pattern however I am utterly confused about how to go about creating only one DB connection that can achieve the three tasks I mentioned earlier. Here's my implementation of the Helper class.
package com.example.userpc.roadtracker;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by USER PC on 5/21/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="location_service.db";
private static final int VERSION=1;
private static final String DB_CREATE="CREATE TABLE `location_service`.`location` ( `id` INT NOT NULL AUTO_INCREMENT , `longitude` DOUBLE NOT NULL , `latitude` DOUBLE NOT NULL , PRIMARY KEY (`id`), UNIQUE (`longitude`, `latitude`)) ENGINE = MyISAM;";
private static SQLiteDatabase mDatabase=null;
private static DatabaseHelper mDatabaseHelper=null;
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
public static DatabaseHelper getInstance(Context context)
{
if(mDatabaseHelper==null)
return new DatabaseHelper(context);
else
return mDatabaseHelper;
}
public SQLiteDatabase getUsableDataBase()
{
if(mDatabase==null)
return this.getWritableDatabase();
else
return mDatabase;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
谢谢.
推荐答案
否,您仍然需要同步访问SQLiteOpenHelper实例的代码块.
No, you still need to synchronize the blocks of your code in which you are accessing your SQLiteOpenHelper instance.
这将是具有Singleton的单个实例,但这并不意味着2个线程将无法访问同一实例.
It will be a single instance with a Singleton, but that doesn't mean 2 threads are not going to be able to access the same instance.
这篇关于将SQLiteOpenHelper类做成单例会使它成为线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!