views:

108

answers:

2

I need some help dealing with three Threads in Android

One thread is the main thread, the other is the GLThread, and the other is a WorkerThread I created to update the game state.

The problem I have is they all need to access the same LinkedList of game objects. Both the GLThread and my WorkerThread only read from the LinkedList, so no problem there, but occasionally I have the main thread adding in another game object to the list.

How can I manage this? I tried using synchronized in front of the functions involved but it really slows down the application.

For some reason, just catching the errors and not rendering or updating the game state that frame, causes it to start lagging permanently.

Anyone have any great ideas?

A: 

There are various ways to do it: if your list is not too large then you can CAS (compare and set) the list which is an atomic operation. This requires that you create a copy of the list, add the item which needs to be added and then CAS without locking. If it the addition only happens occasionally, then it will not be a significant overhead. CAS is a method on an AtomicReference from Java's atomic library... as Software Monkey mentioned the same thing can be achieved with the CopyOnWriteArrayList.

Alternately, you could also take a look at the various containers in Java's concurrency library, or if you want to have a lock-free collection then use the ConcurrentHashMap.

Lirik
+1  A: 

I would suggest a CopyOnWriteArrayList. This copies the backing list when it mutates, but allows unsynchronized reading with the trade-off that you are reading the list from an instant in time with respect to writes.

Software Monkey