Zafar Iqbal
Zafar Iqbal

Reputation: 21

java program a infinite loop in thread cause hundred percent cpu

I am quite new to Threads in Java, I am using an API which is using thread internally and listening data from the counter party, I am putting this data in an queue for further processing. I have created another Thread which is continuously reading this queue for retrieving data and processing and to write the results into text file. I am using while(true) statement to run infinite loop in thread this cause a hundred per cent of CPU usage and if I use sleep(10) in it add up latency which keep on increasing with time as I am receiving about 20 data item in one second.

public void run() { 
    while(true) { 
      try { Thread.sleep(10); } 
      catch (InterruptedException e2) { // TODO Auto-generated catch block 
        e2.printStackTrace(); 
     } 
     if (!(queue.isEmpt())) { 
        Tick quote=queue.take(); 
        processTuple(quote); 
     } 
    } // end while(true) 
  } // end run()

Could anyone suggest me solution where I can reduce CPU usage without adding latency.

Upvotes: 2

Views: 2101

Answers (4)

Roger Gustavsson
Roger Gustavsson

Reputation: 1709

Check out ArrayBlockingQueue.

EDIT:

Example of how to use a queue based on your code:

LinkedBlockingQueue<Tick> queue;

public void run() { 
    while (true) {
        // No need to check the queue. No need to sleep().
        // take() will wait until there's anything available
        Tick quote = queue.take();
        processTuple(quote);
    } 
}

Upvotes: 3

Venkata Raju
Venkata Raju

Reputation: 5215

You may change your code something like this:

BlockingQueue<Tick> queue = ..

public void run() 
{ 
  for (Tick quote; quote = queue.take(); )
  { 
    if (quote == someSpecialObjectToIndicateStop) 
       break; // To stop this thread Or you may catch InterruptedException

    processTuple(quote); 
  } 
} 

See BlockingQueue documentation here

Upvotes: 1

Jeevan Patil
Jeevan Patil

Reputation: 6079

Use queue implementations instead of Threads. See this link to know more about queue implementations. You can use ArrayBlockingQueue.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

Ya. Use a BlockingQueue implementation instead of busy- wait. while(true) will keep scheduling the thread.

Upvotes: 2

Related Questions