My task is to block an object if at least one thread has entered it. I want to use ReentrantLock for this.

And there are two methods that are under this lock:

 private final Lock monitor = new ReentrantLock(); public boolean update(final K idKey, final V newValue) { this.monitor.lock(); try { // что-то там... } finally { this.monitor.unlock(); } } public boolean add(final K idKey, final V newValue) { this.monitor.lock(); try { // что-то там... } finally { this.monitor.unlock(); } } 

Question: if there are two streams, and stream number 1 has already entered the update method and does something there, and stream number 2 wants to enter the add method at this time, will stream number 2 have to wait until stream number 1 has finished? Or will only the body of the update method be blocked?

  • one
    Stream 2 will stop at this.monitor.lock(); and will stay there until stream 1 calls this.monitor.unlock(); . What methods it will take is unimportant. - Regent

1 answer 1

ReentrantLock does not block anything except the thread that caused lock() (if it is in use by another thread).

In your case, thread 2 will be blocked until thread 1 calls unlock() . In this case, stream 1 may cause lock() repeatedly and it will not be blocked.