Search code examples
javamultithreadinglinked-listwait

Random java.util.NoSuchElementException even with using wait()


Could you please tell me in which case this code throw a java.util.NoSuchElementException :

public class StackTest {

    private LinkedList<Object> myList = new LinkedList<Object>();
    public StackTest() {

        Thread testStack = new Thread() {
            @Override
            public void run() {
                while (true)
                { 
                    synchronized (myList)
                    {
                        try {
                            if (myList.size() == 0)
                            {
                                myList.wait();
                            }
                            Object elem = myList.removeLast();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        testStack.start();
    }

    public void enQueue(Object o)
    {
        synchronized(myList)
        {
            myList.addFirst(o);
            myList.notifyAll();
        }
    }
}

My loop is always waiting for the enqueue method to invoke the notifyAll after adding an element. But from time to time, I have a java.util.NoSuchElementException when calling myList.removeLast()


Solution

  • You should stick to the recommended pattern and put your condition in a while to avoid spurious wakeups.

    synchronized (myList) {
        try {
            while (myList.size() == 0) {
                myList.wait();
            }
            Object elem = myList.removeLast();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }