简体   繁体   中英

Acquire an EXCLUSIVE lock on DB

Background

I am updating a DB From a Service at a certain time daily, while this DB is under update and the user tries to open the app I want to hold on and dont display what is going on, though my service is a typical Cron job implemented in the background. What can be done to achieve this? Also I want to acquire a lock on the DB so that the records dont get messed up. Would appreciate any tuts or any related algos in this regard.

Here is how you can lock your database using a ReentrantReadWriteLock .

// Create the lock object
private ReentrantReadWriteLock lockSqliteDB = new ReentrantReadWriteLock();

// Called to update the database
public void updateDatabase() {
    try {
        lockSqliteDB.writeLock().lock();

        // Read and update the database here

    } finally {
        sqliteDB.close();
        lockSqliteDB.writeLock().unlock();
    }
}

// Called to read from the database
public void readDatabase() {
    try {
        lockSqliteDB.readLock().lock();

        // Read from the database here

    } finally {
        sqliteDB.close();
        lockSqliteDB.readLock().unlock();
    }
}

Note that multiple threads will be able to read from the database simultaneously with the read lock. However, a single thread can be writing to the database with the write lock, during which no other threads will be able to read or write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM