0

I am getting a NoSuchElementException sometimes when removing from a queue. Do I need to use locks/waits/some other delay mechanism?

I've provided a rough translation of the code.

Thread with Queue

public void run(){
while(true){
    if(queue.size()>=2){
        a = queue.remove();
        b = queue.remove();

    //DoesSomeWorkHereWhichWorks
    //Writes to MVAR's
    }
}

Thread which writes to the queue

public void run(){
    while(x>0){
        //Does something which works
        QueueThread.add(this);

       //Take from mvars

    }

}

Much appreciated, please go easy on me, i'm new to programming :)

  • 1
    If you have more than one thread doing this, there is no guarantee that the queue.size() > 0 when queue.remove() is called. – Peter Lawrey Feb 25 '16 at 19:03
  • 1
    There's five 'writer' threads and one 'thread with queue'. So shouldn't that be okay because the queue thread will only operate once each time. – Peter File Feb 25 '16 at 19:11
  • This would be a good time to produce an SSCCE. http://sscce.org/ – Solomon Slow Feb 25 '16 at 19:31
  • 1
    You could look into a `BlockingQueue`, whose `put(E e)` and `take()` methods will block until there is space/capacity to add/remove an element. Then you don't need a check on the size, as it will remove an element (or wait until there is one to remove), then remove the second element (or wait until there is one to remove). Unless you actually need to wait until there are 2 or more before removing anything...but you didn't really say the purpose of the program. – Evan LaHurd Feb 26 '16 at 19:32

1 Answers1

2

If your snippet is ok there is a problem because:

if(queue.size()>=2)
    a = queue.remove();
    b = queue.remove();

is equal to writing:

if(queue.size()>=2) {
    a = queue.remove();
}
    b = queue.remove();

About your question, when you have more than one thread you should take into account that every Java statement is decomposed in more than one sub-statement, even a simple statement like i++.

Sub-statements from different threads could interleave during the program execution, and if there is a shared resource between the threads, like your queue, the result could be unpredictable.

You can find a more here.

optimusfrenk
  • 1,271
  • 2
  • 16
  • 34