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
It is convenient to use
ReadWriteLockin this case. As documentation says:The code may look like the following: