robbin
robbin

Reputation: 1954

Signal running thread1 to complete method1 after thread2 enters method2

I have 2 methods which need to function as below.

method1 {
  1. run logic and insert into table1
}

method2 {
  1. wait till other threads finish method1
  2. block future threads from starting method1
  3. update table1
}

The easiest solution would be to synchronize both method1 and method2. Another point of consideration is that method1 can be invoked by multiple threads (>10) and is common operation, while method2 is called very very rarely. So, synchronizing method1 will seriously hamper multiprocessing capability.

I explored the possibility of using ReadWriteLock, with a readLock in method1 and writeLock in method2. But that doesn't help me with #1 in method2, ie. after a writeLock is acquired in method2, I want running threads in method1 to complete before I proceed method2.

Upvotes: 0

Views: 56

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

This is a classic usage of ReadWriteLock.

See Java Concurrency with ReadWriteLock

The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

So when you request a write lock in #1 of method2 it will wait until a time when all read locks have been released by anyone calling method1 before taking the lock and returning.

Taking a write lock essentially performs both #1 and #2 of method2.

Upvotes: 2

Related Questions