Black Magic
Black Magic

Reputation: 2766

My thread doesn't work with my Queue

I'm a noob in Multi threading, so this will propably be a stupid question ;) But I have a thread wich uses a queue that will be filled with commands while the thread is running. The problem I have here, is that the thread doesn't see the changes in the queue, and therefore keeps returning null when I am trying to acces the elements in the queue. Any help with this?

//This method will add an command to the queue
public void sendCommand( String Command )
{
  qe.add(Command);
}

public void run()
{
  while( true )
  {
    while(qe.peek() != null)
    {
      sendCommandToDevice(qe.poll());
    }
  }
}

Upvotes: 1

Views: 219

Answers (3)

assylias
assylias

Reputation: 328568

Use a thread safe queue, such as any of the BlockingQueue implementations, and it should solve your issue.

Upvotes: 1

arcy
arcy

Reputation: 13103

Perhaps there is some kind of problem in the implementation of your queue; I have no other explanation for why the read loop doesn't see changes.

That said, this looks like a bad way to implement this. Your thread will 'spin', chewing up CPU at a great rate, any time it waits for messages to be added. You need something that will notify your reader that there are (possibly) elements added to the queue, rather than polling it continuously. Look up a tutorial on the Object methods wait and notifyAll; the basic idea is that your reader thread executes wait on an object, and that suspends the thread until it is started again with notifyAll. The entire lesson is too big for an SO answer.

Upvotes: 2

Jordan Kaye
Jordan Kaye

Reputation: 2887

Assuming that this is Java or C#, you should mark the Queue as volatile. This will force the concurrently running thread to recheck the value of the queue each time it attempts to access it rather than caching the object.

If you want more information, this post does a pretty good job of explaining the keyword.

Upvotes: 1

Related Questions