梦里风林
  • Introduction
  • Android
    • activity
      • Activity四种启动模式
      • Intent Flag
      • 多task的应用
      • Task和回退栈
    • sqlite
      • 【源码】CursorWindow读DB
      • Sqlite在Android上的一个Bug
    • Chromium
    • ListView读取DB数据最佳实践
    • Android Project结构
    • 一个由Proguard与FastJson引起的血案
    • 琐碎的一些tips
  • Computer Vision
    • 特征提取
    • 三维视觉
    • 计算机视觉常用工具
    • 浅谈深度学习数据集设计
    • 随笔
  • Machine Learning
    • 技巧
      • FaceBook: 1 hour training ImageNet
      • L2 Norm与L2 normalize
    • 实践
      • Pytorch实验代码的亿些小细节
    • 工具
      • Tensorflow学习笔记
      • MXNet踩坑手记
      • PyTorch踩坑手记
      • PyTorch模型剪枝
      • Keras踩坑手记
      • mscnn
      • Matlab
        • Matlab Remote IPC自动化数据处理
    • Papers
      • Classification
      • Re-identification
        • CVPR2018:TFusion完全解读
        • ECCV2018:TAUDL
        • CVPR2018:Graph+reid
        • Person Re-identification
        • CVPR2016 Re-id
        • Camera topology and Person Re-id
        • Deep transfer learning Person Re-id
        • Evaluate
      • Object Detection
        • 读论文系列·干货满满的RCNN
        • 读论文系列·SPP-net
        • 读论文系列·Fast RCNN
        • 读论文系列·Faster RCNN
        • 读论文系列·YOLO
        • 读论文系列·SSD
        • 读论文系列·YOLOv2 & YOLOv3
        • 读论文系列·detection其他文章推荐
      • Depth
      • 3D vision
        • 数据集相关
        • 光流相关
      • Hashing
        • CVPR2018: SSAH
      • 大杂烩
        • CNCC2017 琐记
        • ECCV 2016 Hydra CCNN
        • CNCC2017深度学习与跨媒体智能
        • MLA2016笔记
    • 《机器学习》(周志华)读书笔记
      • 西瓜书概念整理
        • 绪论
        • 模型评估与选择
        • 线性模型
        • 决策树
        • 神经网络
        • 支持向量机
        • 贝叶斯分类器
        • 集成学习
        • 聚类
        • 降维与度量学习
        • 特征选择与稀疏学习
        • 计算学习理论
        • 半监督学习
        • 概率图模型
        • 规则学习
        • 强化学习
        • 附录
  • Java
    • java web
      • Servlet部署
      • 琐碎的tips
    • JNI
    • Note
    • Effective Java笔记
  • 后端开发
    • 架构设计
    • 数据库
    • java web
      • Servlet部署
      • 琐碎的tips
    • Spring boot
    • django
    • 分布式
  • Linux && Hardware
    • Ubuntu安装与初始配置
    • 树莓派相关
      • 树莓派3B+无线网卡监听模式
      • TP-LINK TL-WR703N v1.7 openwrt flashing
  • Python
    • django
    • 原生模块
    • 设计模式
    • 可视化
    • 常用库踩坑指南
  • web前端
    • header div固定,content div填充父容器
    • json接口资源
  • UI
  • kit
    • vim
    • git/github
      • 刷爆github小绿点
    • Markdown/gitbook
      • 琐碎知识点
      • gitbook添加disqus作为评论
      • 导出chrome书签为Markdown
      • Markdown here && 微信公众号
    • LaTex
      • LaTex琐记
    • 科学上网
    • 虚拟机
  • thinking-in-program
    • 怎样打日志
  • 我的收藏
  • 琐记
    • 论文心得
    • 深圳买房攻略
  • 赞赏支持
由 GitBook 提供支持
在本页

这有帮助吗?

  1. Android
  2. sqlite

【源码】CursorWindow读DB

上一页sqlite下一页Sqlite在Android上的一个Bug

最后更新于6年前

这有帮助吗?

执行QUERY

执行SQLiteDatabase类中query系列函数时,只会构造查询信息,不会执行查询。

(query的源码追踪路径)

执行MOVE(里面的FILLWINDOW是真正打开文件句柄并分配内存的地方)

当执行Cursor的move系列函数时,第一次执行,会为查询结果集创建一块共享内存,即cursorwindow

moveToPosition源码路径

FILLWINDOW----真正耗时的地方

然后会执行sql语句,向共享内存中填入数据,

fillWindow源码路径

在SQLiteCursor.java中可以看到

@Override
public boolean onMove(int oldPosition, int newPosition) {
    // Make sure the row at newPosition is present in the window
    if (mWindow == null || newPosition < mWindow.getStartPosition() ||
            newPosition >= (mWindow.getStartPosition() + mWindow.getNumRows())) {
        fillWindow(newPosition);
    }

    return true;
}

如果请求查询的位置在cursorWindow的范围内,不会执行fillWindow,

而超出cursorwindow的范围,会调用fillWindow,

而在nativeExecuteForCursorWindow中,

获取记录时,如果要请求的位置超出窗口范围,会发生CursorWindow的清空:

CopyRowResult cpr = copyRow(env, window, statement, numColumns, startPos, addedRows);  
if (cpr == CPR_FULL && addedRows && startPos + addedRows < requiredPos) {  
// We filled the window before we got to the one row that we really wanted. 
// Clear the window and start filling it again from here.  
// TODO: Would be nicer if we could progressively replace earlier rows.  
window->clear();  
window->setNumColumns(numColumns);  
startPos += addedRows;  
addedRows = 0;  
cpr = copyRow(env, window, statement, numColumns, startPos, addedRows);  
}

CursorWindow的清空机制会影响到多线程读(通常认为不可以并发读写,sqlite的并发实际上是串行执行的,但可以并发读,这里要强调的是多线程读也可能有问题),具体见稍后一篇文章“listview并发读写数据库”。

上面说的这些直观的感受是什么样的呢?大概是这样,

执行query,读10000条数据,很快就拿到了cursor,这里不会卡,

执行moveToFirst,卡一下(fillwindow(0))

moveToPosition(7500),卡一下,因为已经超了cursorwindow的区域,又去fillwindow(7500),

关于fillwindow还有一些奇特的细节,比如4.0以后,fillwindow会填充position前后各一段数据,防止读旧数据的时候又需要fill,感兴趣的同学可以看看各个版本fillwidow的源码。

这里还可以延伸一下,因为高版本的android sqlite对旧版有许多改进,

所以实际开发里我们有时候会把sqlite的源码带在自己的工程里,使得低版本的android也可以使用高版本的特性,并且避开一部分兼容性问题。

CURSOR关闭(显式调用CLOSE()的理由)

追踪源码看关闭

 //SQLiteCursor

super.close();
synchronized (this) {
    mQuery.close();
    mDriver.cursorClosed();
}


//AbstractCursor

public void close() {
    mClosed = true;
    mContentObservable.unregisterAll();
    onDeactivateOrClose();
}

protected void onDeactivateOrClose() {
    if (mSelfObserver != null) {
        mContentResolver.unregisterContentObserver(mSelfObserver);
        mSelfObserverRegistered = false;
    }
    mDataSetObservable.notifyInvalidated();
}


//AbstractWindowedCursor

/** @hide */
@Override
protected void onDeactivateOrClose() {
    super.onDeactivateOrClose();
    closeWindow();
}

protected void closeWindow() {
    if (mWindow != null) {
        mWindow.close();
        mWindow = null;
    }
}



//SQLiteClosable

public void close() {
    releaseReference();
}

public void releaseReference() {
    boolean refCountIsZero = false;
    synchronized(this) {
        refCountIsZero = --mReferenceCount == 0;
    }
    if (refCountIsZero) {
        onAllReferencesReleased();
    }
}

//CursorWindow

@Override
protected void onAllReferencesReleased() {
    dispose();
}

private void dispose() {
    if (mCloseGuard != null) {
        mCloseGuard.close();
    }
    if (mWindowPtr != 0) {
        recordClosingOfWindow(mWindowPtr);
        nativeDispose(mWindowPtr);
        mWindowPtr = 0;
    }
}

跟CursorWindow有关的路径里,最终调用nativeDispose()清空cursorWindow;

当Cursor被GC回收时,会调用finalize:

@Override
protected void finalize() {
    try {
        // if the cursor hasn't been closed yet, close it first
        if (mWindow != null) {
            if (mStackTrace != null) {
                String sql = mQuery.getSql();
                int len = sql.length();
                StrictMode.onSqliteObjectLeaked(
                    "Finalizing a Cursor that has not been deactivated or closed. " +
                    "database = " + mQuery.getDatabase().getLabel() +
                    ", table = " + mEditTable +
                    ", query = " + sql.substring(0, (len > 1000) ? 1000 : len),
                    mStackTrace);
            }
            close();
        }
    } finally {
        super.finalize();
    }
}

然而finalize()并没有释放CursorWindow,而super.finalize();里也只是解绑了观察者,没有去释放cursorwindow

所以不调用cursor.close(),最终会导致cursorWindow所在的共享内存(1M或2M)泄露。