user1508419
user1508419

Reputation: 333

How to break an infinite loop

this is my piece of code:

// TODO Auto-generated method stub
        try
        {
            Socket clientSocket = new Socket("localhost", 8888);

            ObjectOutputStream ous = new ObjectOutputStream(clientSocket.getOutputStream());

            while(sending)
            {
                Statistics statsData = setStatisticsData();
                ous.writeObject(statsData);

                Thread.sleep(5000);
            }           
        }
        catch(UnknownHostException uhe) 
        {
            uhe.printStackTrace();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        } 
        catch (InterruptedException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

it's the client.it'll sending in an infinite loop an object Statistics. I would implement a way to break this infinite loop through input (es. press a button in the keyboard).ok can I do?how can i break an infinite loop?

Upvotes: 1

Views: 1160

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

If this is a separate thread:

Thread statisticsSendingThread = ...

Then simply interrupt it:

statisticsSendingThread.interrupt();

InterruptedException will be thrown, escaping from the loop.

I see you already have a boolean sending flag. It will work as well, but with 5 second delay in worst case. Also make sure it is volatile - or better, use isInterrupted() method of thread. But interrupting the thread using interrupt() is by far the easiest way (no extra coding required). And your loop can be truly infinite (while(true) although with while(!isInterrupted())).


BTW your setStatisticsData() should probably be named getStatisticsData().

Upvotes: 4

Sreehari Puliyakkot
Sreehari Puliyakkot

Reputation: 736

while(sending) 
{ 
    Statistics statsData = setStatisticsData(); 
    ous.writeObject(statsData); 
    Thread.sleep(5000);
    if(EXIT_FLAG == true)
       sending = false;
}    

EXIT_FLAG can be a static variable that can be updated from outside. You may also want to run this infinite loop in a separate Thread. Read more about how to share data between Threads.

Upvotes: -1

NominSim
NominSim

Reputation: 8511

You'll have to do them on separate threads, and since you are looking for user input it would probably be best to move your code to some asynchronous thread, then simply on input set your sending bool to false or interrupt the thread YourThread.interrupt();

Upvotes: 0

Related Questions