Android使用SQLITE3 WAL模式

sqlite是支持write ahead logging(WAL)模式的,开启WAL模式可以提高写入数据库的速度,读和写之间不会阻塞,但是写与写之间依然是阻塞的,但是如果使用默认的TRUNCATE模式,当写入数据时会阻塞android中其他线程或者进程的读操作,并发降低。 相反,使用WAL可以提高并发。 由于使用WAL比ROLLBACK JOURNAL的模式减少了写的I/O,所以写入时速度较快,但是由于在读取数据时也需要读取WAL日志验证数据的正确性,所以读取数据相对要慢。 所以大家也要根据自己应用的场景去使用这种模式。

那么在android中如何开启WAL模式呢?

看SQLiteDatabase开启WAL的核心方法源码。

public boolean enableWriteAheadLogging() {
        // make sure the database is not READONLY. WAL doesn't make sense for readonly-databases.
        if (isReadOnly()) {
            return false;
        }
        // acquire lock - no that no other thread is enabling WAL at the same time
        lock();
        try {
            if (mConnectionPool != null) {
                // already enabled
                return true;
            }
            if (mPath.equalsIgnoreCase(MEMORY_DB_PATH)) {
                Log.i(TAG, "can't enable WAL for memory databases.");
                return false;
            }

            // make sure this database has NO attached databases because sqlite's write-ahead-logging
            // doesn't work for databases with attached databases
            if (mHasAttachedDbs) {
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG,
                            "this database: " + mPath + " has attached databases. can't  enable WAL.");
                }
                return false;
            }
            mConnectionPool = new DatabaseConnectionPool(this);
            setJournalMode(mPath, "WAL");
            return true;
        } finally {
            unlock();
        }
    }

在源码的注释中是这样写到:“This method enables parallel execution of queries from multiple threads on the same database.” 通过此方法可以支持多个线程并发查询一个数据库。 并在注释中给出了实例代码如下:

SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", 
cursorFactory,CREATE_IF_NECESSARY, myDatabaseErrorHandler);
 db.enableWriteAheadLogging();

通过调用db.enableWriteAheadLogging即可开启WAL模式。 在enableWriteAheadLogging方法中关注的核心点:

mConnectionPool = new DatabaseConnectionPool(this);
setJournalMode(mPath, "WAL");

1.创建数据库连接池,由于要支持并发访问所以需要连接池的支持。 

2.调用setJournalMode设置模式为WAL.

当开启了WAL模式之后,事务的开始需要注意,在源码的注释是这样写到。

Writers should use {@link #beginTransactionNonExclusive()} or
     * {@link #beginTransactionWithListenerNonExclusive(SQLiteTransactionListener)}

调用者需要使用beginTransactionNonExclusive或者beginTransactionWithListenerNonExclusive来开始事务,也就是执行:BEGIN IMMEDIATE; 支持多并发。

注:关于EXCLUSIVE与IMMEDIATE模式请参考我的另一篇博客 http://blog.csdn.net/degwei/article/details/9672795

当开启了WAL模式更新数据时,会先将数据写入到*.db-wal文件中,而不是直接修改数据库文件,当执行checkpoint时或某个时间点才会将数据更新到数据库文件。当出现rollback也只是清除wal日志文件,而ROLLBACK JOURNAL模式,当数据有更新时,先将需要修改的数据备份到journal文件中,然后修改数据库文件,当发生rollback,从journal日志中取出数据,并修改数据库文件,然后清除journal日志。 从以上流程来看 WAL在数据更新上I/0量要小,所以写操作要快。

当开启了WAL模式磁盘中是这样的文件格式,当数据文件名为:test时 如下图:


图中红色部分为WAL的日志文件。

那么WAL日志中的数据何时更新到数据库文件中,刚才提到当手动执行checkpoint时或者由当前线程的某个时间点提交。

如何手动执行checkpoint,看SQLiteDatabase.endTransaction源码:

/**
     * End a transaction. See beginTransaction for notes about how to use this and when transactions
     * are committed and rolled back.
     */
    public void endTransaction() {
        verifyLockOwner();
        try {
            ...
            if (mTransactionIsSuccessful) {
                execSQL(COMMIT_SQL);
                // if write-ahead logging is used, we have to take care of checkpoint.
                // TODO: should applications be given the flexibility of choosing when to
                // trigger checkpoint?
                // for now, do checkpoint after every COMMIT because that is the fastest
                // way to guarantee that readers will see latest data.
                // but this is the slowest way to run sqlite with in write-ahead logging mode.
                if (this.mConnectionPool != null) {
                    execSQL("PRAGMA wal_checkpoint;");
                    if (SQLiteDebug.DEBUG_SQL_STATEMENTS) {
                        Log.i(TAG, "PRAGMA wal_Checkpoint done");
                    }
                }
                // log the transaction time to the Eventlog.
                if (ENABLE_DB_SAMPLE) {
                    logTimeStat(getLastSqlStatement(), mTransStartTime, COMMIT_SQL);
                }
            } else {
                ...
            }
        } finally {
            mTransactionListener = null;
            unlockForced();
            if (false) {
                Log.v(TAG, "unlocked " + Thread.currentThread()
                        + ", holdCount is " + mLock.getHoldCount());
            }
        }
    }

在源码注释是这样写到:“if write-ahead logging is used, we have to take care of checkpoint.” 如果使用了WAL模式,那么就会执行checkpoint,当mConnectionPool != null时表示使用了WAL模式,也只有当WAL模式下才会有数据库连接池。 执行PRAGMA wal_checkpoint;即:将wal日志同步到数据库文件。 也就是当我们执行endTransaction时才会提交checkpoint。

在android中默认为TRUNCATE模式 , 请看如下源码:

public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags,
            DatabaseErrorHandler errorHandler) {
        SQLiteDatabase sqliteDatabase = openDatabase(path, factory, flags, errorHandler,
                (short) 0 /* the main connection handle */);

        // set sqlite pagesize to mBlockSize
        if (sBlockSize == 0) {
            // TODO: "/data" should be a static final String constant somewhere. it is hardcoded
            // in several places right now.
            sBlockSize = new StatFs("/data").getBlockSize();
        }
        sqliteDatabase.setPageSize(sBlockSize);
        sqliteDatabase.setJournalMode(path, "TRUNCATE");

        // add this database to the list of databases opened in this process
        synchronized(mActiveDatabases) {
            mActiveDatabases.add(new WeakReference<SQLiteDatabase>(sqliteDatabase));
        }
        return sqliteDatabase;
    }

通过sqliteDatabase.setJournalMode(path, "TRUNCATE");设置为TRUNCATE模式。


关于WAL模式下数据库连接池的解析,请看另外一篇blog。



  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值