数据库锁定异常 [英] Database locked exception

查看:109
本文介绍了数据库锁定异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中创建了一个包含5个表的数据库.我的数据库正在从不同的线程更新.当我看到日志时,可以看到打开数据库(如果已打开)时发生数据库锁定异常.

I have created a database in my application with 5 tables. my database is being updated from different threads. When i see the log i can see that there are database locked exception while opening the database if it is already open.

我的一位朋友建议我始终使用内容提供程序来避免此问题.据他说,内容提供商自行管理并发问题?

One of my friend suggested me to always use content provider to avoid this issue. According to him content provider manages concurrency issues on its own?

如果我们不想与其他应用程序共享数据,使用内容提供程序是否是一个好习惯?

Is it a good practice to use content provider if we don't want to share data to other applications?

推荐答案

我认为在大多数情况下使用读写锁就足够了.

I think using a read-write lock is enough in most cases.

假设您编写了以下内容,

Suppose you have written the following,

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MyDatabase extends SQLiteOpenHelper
{
    private static final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);

    private static void beginReadLock()
    {
        rwLock.readLock().lock();
    }

    private static void endReadLock()
    {
        rwLock.readLock().unlock();
    }

    private static void beginWriteLock()
    {
        rwLock.writeLock().lock();
    }

    private static void endWriteLock()
    {
        rwLock.writeLock().unlock();
    }

然后您可以按照以下步骤完成任务.

then you can do your task like the following.

    public static void doSomething()
    {
        SQLiteDatabase sldb = null;

        try
        {
            beginReadLock();

            MyDatabase mydb = new MyDatabase();
            sldb = mldb.getReadableDatabase();
            ......
        }
        catch (Exception e)
        {
            ......
        }
        finally
        {
            if (sldb != null)
            {
                try
                {
                    sldb.close();
                }
                catch (Exception e) {}
            }

            endReadLock();
        }
    }

使用 beginReadLock() endReadLock()封闭读取操作.同样,使用 beginWriteLock() endWriteLock()封闭写操作.

Enclose read operations with beginReadLock() and endReadLock(). Likewise, enclose write operations with beginWriteLock() and endWriteLock().

一个月前,通过上述解决方案,我可以解决自己的数据库锁定问题,其中多个线程试图同时读写数据库.

Months ago, by the solution described above, I could solve my own database-lock issue where multiple threads were trying to read/write-open a database simultaneously.

这篇关于数据库锁定异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆