Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading - why do we do use while(true) while waiting

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

like image 357
topgun_ivard Avatar asked Jun 27 '11 08:06

topgun_ivard


2 Answers

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.

like image 180
Swaranga Sarma Avatar answered Oct 07 '22 08:10

Swaranga Sarma


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*/ 
 }
}
like image 42
L.Butz Avatar answered Oct 07 '22 09:10

L.Butz