0

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.

lppier
  • 1,927
  • 3
  • 24
  • 62

3 Answers3

1

The ArrayList class is not Thread Safe.

Use Collections.synchronizedList() instead of ArrayList.

arodriguezdonaire
  • 5,396
  • 1
  • 26
  • 50
1

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)
    ..
}
Jason Chueh
  • 361
  • 1
  • 7
  • Hi Jason, sorry but what is the difference between the two here? – lppier Jul 31 '15 at 01:08
  • 1
    The first one is a compiler sugar. Since the list is a collection, compiler translates the for loop with iterator. Iterator is the one who throws the exception. However, if you store your data in an array, the exception will not be thrown. Compiler will use the regular for loop if your data is a simple array. – Jason Chueh Jul 31 '15 at 03:20
1

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.

Community
  • 1
  • 1
Loganathan Mohanraj
  • 1,736
  • 1
  • 13
  • 22