NoSuchElementException on non empty list

I have a runnable created this way:

private Runnable _animationScriptRunnable = new Runnable() {
    public void run() {
        synchronized (AnimationManager.this) {
            while (!_stopRunning && !_animationScriptStack.isEmpty()) {
                Class key = _animationScriptStack.removeFirst();
                if (isAnimationExist(key) && isAnimationActivated(key)) {
                    AAnimation animation = _animationsClassTable.get(key);
                    animation.doBeforeAnimation();
                    animation.onAnimationBeginning();
                    do {
                        animation.onAnimation();
                    } while (isAnimationActivated(key) && animation.isAnimationRecurent() && !_stopRunning);
                    animation.onAnimationEnding();
                    animation.doAfterAnimation();
                }
            }
        }
    }
};

As you can see, I check in a synchronized block that my stack (_animationScriptStack, created as a LinkedList<Class<?>> _animationScriptStack) is not empty, and if it's not, I remove the first element. But, sometimes, I have a java.util.NoSuchElementException, on the removeFirst() call.

Can someone explain me why?

Answers


LinkedList is not thread safe and probably this is causing un-expected results in your code.

You need to use ConcurrentLinkedQueue in this case as you are trying to access a list in a Thread. Please look at it, I guess this is what you need.


Need Your Help

Manually parse part of a response when using Retrofit

android json gson retrofit

I'm working with a REST API that returns a JSON document that starts as follows and includes a "collection" of items with string IDs like "ABC". Note the "routes" field, which contains a series of ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.