lppier
lppier

Reputation: 1987

Android: Sharing lists between two threads

I'm doing an app in which I have 2 views which extend from SurfaceView, called CanvasView.

I have a left CanvasView, and a right CanvasView. Both these CanvasView instantiate a UIThread, which extends from Thread. The CanvasView itself is passed into the thread like this:

public void surfaceCreated(SurfaceHolder holder) {
  uiThread = new UIThread(this);
  uiThread.setRunning(true);
  uiThread.start(); 
}

In each CanvasView, onDraw() , I do an access to a list. This list basically consists of a list of things to draw, which are essentially the same on both left and right canvases.

for (CharSequence line : lineList) {
... 
..
}

Whenever my app needs to draw the items in lineList, it crashes saying java.util.ConcurrentModificaitonException.

What is the correct way to "share" the Arraylist lineList between the two threads?

Thank you.

Upvotes: 0

Views: 161

Answers (3)

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

List is not thread safe and when multiple threads attempts to modify the same list, it will end up with concurrent modification exception.

Use ConcurrentLinkedQueue or CopyOnWriteArrayList.

Refer the link - Is there a concurrent List in Java's JDK?

Collections.synchronizedList() is an other alternative which will provide the synchronized access to the list.

Upvotes: 1

Jason Chueh
Jason Chueh

Reputation: 361

Don't use the simplified version of for loop

for (CharSequence line : lineList) {
    ... 
    ..
}

Instead, use the traditional one. However, you have to handle data consistency by yourself.

for (int i = 0; i < lineList.size(); i++) {
    CharSequence line = lineList.get(i)
    ..
}

Upvotes: 1

arodriguezdonaire
arodriguezdonaire

Reputation: 5562

The ArrayList class is not Thread Safe.

Use Collections.synchronizedList() instead of ArrayList.

Upvotes: 1

Related Questions