demand
FooService:
- methodA
- methodB
- methodC
An and B / C are mutually exclusive, that is, they cannot operate at the same time, but B and C can operate at the same time
obviously synchronized
does not support it because it is mutually exclusive
- synchronized void methodA
- synchronized void methodB
- synchronized void methodC
A solution
adopt read-write locks as follows
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
public void methodA() {
rwl.writeLock().lock();
// do something here
rwl.writeLock().unlock();
}
public void methodB() {
rwl.readLock().lock();
// do something here
rwl.readLock().unlock();
}
I don"t know that there is no other solution in Java that can meet the above requirements, that is, one method is mutually exclusive with other methods, but whether the other methods can operate at the same time
or can only use read-write locks