Robb1
Robb1

Reputation: 5025

How to avoid concurrent execution of two methods?

I have two synchronized methods, each of them is being executed by a different Thread.

public synchronized ResultSet dbExecuteQuery(String queryStmt);

public synchronized void dbExecuteUpdate(String queryStmt);

How can I make sure their execution won't "overlap"?

One solution that comes to my mind is the following:

public synchronized ResultSet dbExecute(String queryStmt, boolean isUpdate) {
if (isUpdate) {
    dbExecuteUpdate(queryStmt);
    return null;
} else
    return dbExecuteQuery(queryStmt);
}

But it means I would have to change all code used in the whole project. Is there a cleaner way to do it?

Upvotes: 0

Views: 272

Answers (1)

daniu
daniu

Reputation: 15028

You can add a dedicated synchronization object:

class YourClass {
    Object syncObject = new Object();
    public ResultSet dbExecuteQuery(String queryStmt) {
        synchronized(syncObject) {
            // your code
        }
    }

    public void dbExecuteUpdate(String queryStmt) {
        synchronized(syncObject) {
            // other code
        }
    }
}

But it's probably better to use a ReentrantLock.

class YourClass {
    private Lock lock = new ReentrantLock();
    public ResultSet dbExecuteQuery(String queryStmt) {
        lock.lock();
        // your code
        lock.unlock();
    }

    public void dbExecuteUpdate(String queryStmt) {
        lock.lock();
        // other code
        lock.unlock();
    }
}

Actually, since one is a read and one a write, you probably want to use ReadWriteLock.

class YourClass {
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public ResultSet dbExecuteQuery(String queryStmt) {
        lock.readLock().lock();
        // your code
        lock.readLock()..unlock();
    }

    public void dbExecuteUpdate(String queryStmt) {
        lock.writeLock()..lock();
        // other code
        lock.writeLock().unlock();
    }
}

This way you can have several threads reading concurrently:

The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

Upvotes: 2

Related Questions