Senior
Why did you choose wait/notify specifically, rather than ReentrantLock?
sobes.tech AI
Answer from AI
The choice between wait/notify and ReentrantLock depends on the specific requirements and context of the task.
Why wait/notify:
- These are basic synchronization mechanisms in Java, built into Object, requiring no additional objects.
- Suitable for simple cases where you just need to suspend a thread until a certain event occurs.
- Can be slightly more efficient in very simple scenarios due to the absence of extra wrappers.
Why not ReentrantLock:
- ReentrantLock offers more flexible features, such as tryLock, the ability to interrupt waiting, and condition variables.
- If the task does not require these advanced features, using ReentrantLock might be excessive.
Thus, if the task is simple and does not require advanced lock management, wait/notify is a lighter and more straightforward tool. If flexibility and additional functions are needed, ReentrantLock should be used.
Example of using wait/notify:
synchronized (lock) {
while (!condition) {
lock.wait();
}
// action after the condition is met
}
// In another thread
synchronized (lock) {
condition = true;
lock.notify();
}