I have a number of different sockets connecting to my code that are all each listening on independent threads. Time may go by before an object is passed to any of these sockets. So I have a while(running) loop that runs basically forever.
Then to synchronize all the different threads, I have an ArrayBlockingQueue. Whenever a socket/thread combo receives an object, I then add that object to the ArrayBlockingQueue (since it is automatically synchronized for me). Then in the while(running) code, I remove the object and process it.
The problem is that the processor goes crazy in that while(running) loop... Ideally I would like to block on starting to process all the objects until the ArrayBlockingQueue actually has something to process in hopes that the processor doesn't keep running.
Do you know if this is possible?
Here is my current code that causes the processor to spin up and waste cycles...
@Override
public void run()
{
while(running)
{
while(messageQueue.size() > 0)
{
Object o = messageQueue.remove();
}
}
}
Here is what I would like...
@Override
public void run()
{
while(running)
{
messageQueue.BlockUntilSomethingInHere();
while(messageQueue.size() > 0)
{
Object o = messageQueue.remove();
}
}
}
while(messageQueue.size() > 0): Just remove that.remove()is nonblocking. It has to be replaced by a blocking method to get rid of the pretest.