Synchronized issue
Hi,
I have a synchronized block and Im sending a request to another application (blocking operation). So until i get response, I need to wait(), so that i wont end up consuming too much CPU. I want to wait() but i do also like to ensure that no other thread will enter this synchronized black in the mean time.
Because, i just want one thread to do this complete process and then only let the other thread come in.
I dont know how to stop other Thread acquiring lock while first thread is in waiting state.
..............Something..........
Collection col = null;
.........Some code.........
synchronized(lock)
{
send(col);
while(col == null)
{
lock.wait();
}
//Do further stuff
}
..........
void recieveResponse()
{
synchronized(lock)
{
// col is populated
lock.notify
}
}
[924 byte] By [
karachitea] at [2007-11-27 11:12:12]

# 1
You have a design issue which is beyond the scope of this forum.
You can always use two locks:
sync(lock1)
send(col);
while(col == null)
{
sync(lock2)
lock2.wait();
}
Now this is a little messy and you may end up with deadlock issues but is should work.
# 5
The code I gave you is awful but it demonstrates a solution.
lock2 is only for waiting/notifying. While the thread is waiting, it is holding the lock for lock1. Therefore, any resources you want to restrict access to should be protected by lock1.
Holding lock1 while in a wait state is bad programming, especially since there is no time out in the wait(). But in any case, it is a way.
# 6
You can always use a Semaphore or a Latch. Or better yet. Use a BlockingQueue with a Consumer-Producer pattern. Would that help?
...
while(col == null) {
gateLatch = new CountDownLatch(1);
gateLatch.await();
}
void recieveResponse() {
synchronized(lock) {
// col is populated
gateLatch.countDown();
}
}