`
hemowolf
  • 浏览: 151931 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

游标泄漏(CursorLeak)

阅读更多

  通常,使用try-finally来确保程序异常时能正常关闭游标。

 

Cursor cursor = null;
try {
	cursor = getContentResolver().query(URI, .....);
        //dosomething
} finally {
	if (cursor != null) {
		cursor.close();
	}
}

 典型的一种写法,但并不能确保游标不泄漏。下面是采用这种写法产生的一出异常:

 ERROR/CursorLeakDetecter(11085):

android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here 

at android.content.ContentResolver.query(ContentResolver.java:323)

  如果您稍不留意不会怀疑这块代码的问题,因为try-finally写法不存在逻辑上的问题。
  由于这里未考虑到多线程场景,try-finally并不能保证query打开游标在dosomething时,被其他线程再次调用query打开游标。所以当遇到存在多线程的调用时必须对游标打开到关闭时间段添加锁,即这里是对try-finally块加锁。
 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics