In most of the threading examples in Java, there is common use of a while(true) block like this:
while(true) {
try {
wait()
} catch (Exception ex) {
/*do something*/
}
}
What is the purpose of using while (true) ? Under what kind of scenarios are they particularly useful? Client/Server communications?
Thanks,
- Ivar
This kind of construct is used when we create Thread pools and re-usable threads. Basically the while(true)
construct prevents the Threads of the pool to ever exit.
An example would be a Producer-Consumer situation where Threads wait()
till until the queue is empty and as soon as the queue has data, they are notify()
ied and one of the thread consumes the data from the queue and does the processing and then goes back to wait()
for additional data to arrive again.
while(true) is useful if you want to do something all the time while your code is running and you don't know how often you have to do it.
Client/Server Communication is one scenario. Other scenarios are animations of games or keeping some values always up to date.
A Thread is seperated from the other code, so your application would not hang by using while(true).
It is usefull to add an exit-flag to your while(true)-loop, so you can stop it if you want to.
Boolean isExit = false; //set this value to true when needed.
while(true) {
try {
if(isExist){
break;
}
wait()
} catch (Exception ex) {
/*do something*/
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With