MikaelW
MikaelW

Reputation: 1205

mutually exclusive java method execution (not all)

I have a java class with 4 methods:

public void method_A() {   ...   }

public void method_B1() {   ...   }

public void method_B2() {   ...   }

public void method_B3() {   ...   }

The instance of this class is used by many multiple threads that are interested in calling the methods B1 B2 and B3. Having those execute concurrently is absolutely fine

However, every now and then method_A() is called internally and the 3 other should never be called at that time. When method_A() runs, no other method should be running, they should wait with some sort of lock till method_A() has completed.

Really not sure how that translate to code. Many Thanks

Upvotes: 2

Views: 348

Answers (1)

user3707125
user3707125

Reputation: 3484

This is a good case for ReentrantReadWriteLock. It allows simultaneous reads (B1, B2, B3), but writes (A) block both reads and writes.

You should add:

private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

And in B* methods:

lock.readLock().lock();
try {        
    // method code
} finally {
    lock.readLock().unlock();
}

In A:

lock.writeLock().lock();
try {
    // method code
} finally {
    lock.writeLock().unlock();
}

Upvotes: 7

Related Questions