0

In a multithreaded environment I have a Singleton with a static ArrayList.

Let's say one thread gets the instance and is doing a "for" loop to the ArrayList. Just reading. No updates. This might take sometime to complete. While this happens, another thread updates the ArrayList.

What will happen to the loop (first thread)? Ideally I would like the "for" loop to complete with "old" data and if I get the instance again, then to get the new set of data.

Is the trick in this case to not use volatile ? Or create a new ArrayList from the static ArrayList for the "for" loop? Or... ?

user2287359
  • 497
  • 1
  • 5
  • 16
  • 1
    There are a lot of resources here on stackoverflow discussing this: http://stackoverflow.com/questions/2715983/concurrent-threads-adding-to-arraylist-at-same-time-what-happens for instance. – jontro May 10 '13 at 15:46
  • ArrayList is not thread safe. You need to synchronize every access to the list to have predictable behavior, or use a concurrent list (from the package java.util.concurrent). I would say that, if you have to ask this, you shouldn't deal with multi-threading problems. Multi-threading is really hard. Read *Java concurrency in Practice* by Brian Goetz. – JB Nizet May 10 '13 at 16:01

2 Answers2

1

It looks like using a CopyOnWriteArrayList might be the way to go though costly on memory

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

user2287359
  • 497
  • 1
  • 5
  • 16
-3

It's better to use vector in a multi threading environment instead of ArrayList. The discuss between vector and ArrayList: http://www.javaworld.com/javaqa/2001-06/03-qa-0622-vector.html

Zhenyi Luo
  • 61
  • 5
  • 1
    Using a Vector won't make the iteration work fine is another thread adds something to it while iterationg. You'll get a predictable ConcurrentModificationException, that's all. And Vector really shouldn't be used anymore. If you need a synchronized list (which is, most of the time, not sufficient), use Collections.synchronizedList(). – JB Nizet May 10 '13 at 16:08