Juan Gil
Juan Gil

Reputation: 67

Write locks have priority to access the critical region in a java readWrite lock?

I need writers threads to have priority to access critical region over readers threads, can I use the ReadWriteLock interface to do this?

Upvotes: 0

Views: 353

Answers (1)

BeUndead
BeUndead

Reputation: 3618

While not directly with a ReadWriteLock, the simplest, in-built approach for something like this would probably be a Semaphore, which does support fairness. Creating a fair Semaphore, with an (effectively) unlimited number of permis should suffice:

private static final Semaphore lock = new Semaphore(Integer.MAX_VALUE, true);

public void doReadLocked() throws InterruptedException {

    // 'Read' lock only acquires one permit, but since there are A LOT,
    // many of them can run at once.
    lock.acquire();
    try {
        // Do your stuff in here...
    } finally {

        // Make sure you release afterwards.
        lock.release();
    }
}

public void doWriteLocked() throws InterruptedException {

    // 'Write' lock demands ALL the permits.  Since fairness is set, this
    // will 'take priority' over other waiting 'read'ers waiting to acquire
    // permits.
    lock.acquire(Integer.MAX_VALUE);
    try {
        // Do your stuff in here...
    } finally {

        // Make sure you release afterwards.
        lock.release(Integer.MAX_VALUE);
    }
}

Upvotes: 2

Related Questions