Can a thread call wait() on two locks at once in Java (6)
- by Dr. Monkey
I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify().
I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of:
synchronized(token1) {
synchronized(token2) {
token1.wait();
token2.wait(); //won't run until token1 is returned
System.out.println("I got both tokens back");
}
}
In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at).
A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity.