前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android使用SQLITE3 WAL

Android使用SQLITE3 WAL

作者头像
py3study
发布2020-01-08 18:45:04
1.8K0
发布2020-01-08 18:45:04
举报
文章被收录于专栏:python3python3

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

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

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

代码语言:javascript
复制
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.” 通过此方法可以支持多个线程并发查询一个数据库。 并在注释中给出了实例代码如下:

代码语言:javascript
复制
SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", 
cursorFactory,CREATE_IF_NECESSARY, myDatabaseErrorHandler);
 db.enableWriteAheadLogging();

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

代码语言:javascript
复制
mConnectionPool = new DatabaseConnectionPool(this);
setJournalMode(mPath, "WAL");

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

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

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

代码语言:javascript
复制
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时 如下图:

wKiom1R5uCGxWAowAAAq7mW3ptI158.jpg
wKiom1R5uCGxWAowAAAq7mW3ptI158.jpg

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

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

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

代码语言:javascript
复制
/**
     * 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模式 , 请看如下源码:

代码语言:javascript
复制
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模式。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档