Fizzics
Fizzics

Reputation: 43

How to avoid NullPointerException in ArrayList with 2 threads

I'm creating an Android game and I encountered a problem. I have 2 threads: OpenGL thread and game loop. I use ArrayLists to store my renderable objects and here's the problem. Sometimes I need to delete these objects in game thread and sometimes it causes OpenGL thread to get NullPointerException because, as I understand, it goes through the collection and suddenly an element gets deleted. I think I should let OpenGL thread delete objects but is there any other solution and what if game loop will start to get null elements? Maybe I can make synchronize threads somehow though I still don't understand how "synchronized" works. Thanks.

Will this help? And should I put it everwhere I do something with my ArrayList?

synchronized (arrayListName) 
{ 
    arrayListName.remove(object); 
}

Upvotes: 0

Views: 935

Answers (2)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

I still don't understand how "synchronized" works

That is something you will need to remedy. The concurrency constructs within Java including synchronized are fundamental concepts. I would recommend picking Effective Java, 2nd ed.

http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683

One basic idea is that if you have an atomic operation where one thread reads a list item, then the other thread reads the list item, you need to lock that with a binary semaphore - the simplest way of which is to use the Java synchronized construct.

A less naive approach might be to have thread one pull the value from the list, do what it needs to do, then "pass" the value to thread 2, for example, by adding the item to a queue owned by thread 2.

Describing the "right" solution for your application is almost impossible without intimately knowing the code. I'm just making wild guesses.

Upvotes: 2

pjco
pjco

Reputation: 3836

Jeffery's answer is correct but to sum up what the book will say:

"Use java.util.concurrent whenever needed." (paraphrasing)

Basically, don't re-create the wheel. The java.util.concurrent package is a collection of very well optimized thread safe classes like the ConcurrentHashMap

Have a look at this related StackOverflow question:

https://stackoverflow.com/questions/10395903/why-is-there-not-concurrent-arraylist-in-java-util-concurrent-package

Further reading:

http://www.ibm.com/developerworks/java/library/j-5things4/index.html

http://developer.android.com/reference/java/util/concurrent/package-summary.html

Upvotes: 0

Related Questions