I’m just getting started with Threads in Java so this might be a basic question, but I couldn’t find the answer online.
I have two threads that can call one synchronized function. The way I understand it, if the second thread calls it while the first thread has already called it, the second thread will wait until the first thread is done before calling it. However, I don’t want the second thread to call it at all.
Then the easiest way is to use an explicit lock (
ReentrantLock) and call itstryLock()method.If it returns true, then it means that no other thread has the lock, and the current thread acquired it.
If it returns false, it means that another thread holds the lock, and you should not call the method.
Remember to always call
unlock()in a finally block, to make sure the lock is released even in case an exception is thrown.