Search code examples
javamultithreadingconcurrencyjava-threadslocks

Allow concurrent executions of two methods but not both at the same time


I have two instance methods method1 and method2 of an singleton object. method1 can be run concurrently by separate threads. Meaning we can have 5 threads each running method1 at the same time or 1 thread running method2 at the same time.

I want to prevent method1 from running when method2 is running and method2 from running when method1 is running.

I thought about synchronizing both methods like the code below, this solves the issue where both methods can't be executed at the same time, but it will also prevent my 5 threads from running method1 simultaneously, even if method2 is not running.

void synchronized method1() {
     //do something
}

void synchronized method2() {
    //do other thing
}

First time using java multi-threading so appreciate some advice, thanks.

EDIT: seems like readWriteLock is the way to go


Solution

  • It is convenient to use ReadWriteLock in this case. As documentation says:

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

    The code may look like the following:

      ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
      void method1() {
        final var readLock = lock.readLock();
        try {
          readLock.lock();
          //do something
        }
        finally {
          readLock.unlock();
        }
      }
    
      void method2() {
        final var writeLock = lock.writeLock();
        try {
          writeLock.lock();
          //do other thing
        }
        finally {
          writeLock.unlock();
        }
      }