android SQLite多线程并发访问

背景

多线程情况下,进行SQLite操作时容易抛出打开正在关闭的数据库的异常,并且重复开关耗费性能

解决

在打开和关闭数据时通过计数的方式防止重复打开和重复关闭,保证多个线程同时访问时只打开和关闭数据库一次。

代码

private synchronized SQLiteDatabase getWritableDatabase() {
    if (dbCounter.incrementAndGet() == 1) {
        // Opening new database
        database = helper.getWritableDatabase();
    }
    return database;
}

private synchronized void closeDb() {
    if (dbCounter.decrementAndGet() == 0 && database != null) {
        // Closing database
        database.close();
    }
}
发布了26 篇原创文章 · 获赞 0 · 访问量 1113

猜你喜欢

转载自blog.csdn.net/Plx0303sunny/article/details/104009301