Class clazz
has two methods methodA()
and methodB()
.
How to ensure that
methodB
is "blocked" if some threads are inmethodA
in Java (I am using Java 8)?
By "blocking methodB", I mean that "wait until no threads are in methodA()". (Thanks to @AndyTurner)
Note that the requirement above allows the following situations:
- Multiple threads are simultaneously in
methodA
. - Multiple threads are in
methodB
while no threads are inmethodA
. - Threads in
methodB
does not prevent other threads from enteringmethodA
.
My trial: I use StampedLock lock = new StampedLock
.
- In
methodA
, calllong stamp = lock.readLock()
- Create a new method
unlockB
and calllock.unlockRead(stamp)
in it. - In
methodB
, calllong stamp = lock.writeLock()
andlock.unlockWrite(stamp)
.
However, this locking strategy disallows the second and the third situations above.
Edit: I realize that I have not clearly specified the requirements of the synchronization between methodA
and methodB
. The approach given by @JaroslawPawlak works for the current requirement (I accept it), but not for my original intention (maybe I should first clarify it and then post it in another thread).