-1

I want to add information to a List and that information is gathered from multiple threads. The threads do not need to pull data from the list. Is it safe to have a regular ArrayList or LinkedList? Or what other ways can I do this?

mumbly123
  • 19
  • 2
  • The regular collections are not inherently thread safe. Simplest way is to lock around access to a list – Rotem Oct 23 '19 at 21:46
  • You can use [CopyOnWriteArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html). Similar question: https://stackoverflow.com/a/8203913/2928853 – jrook Oct 23 '19 at 21:47
  • 1
    Documentation: [ArraList](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/ArrayList.html) and [LinkedList](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/LinkedList.html): "**Note that this implementation is not synchronized.** If multiple threads access an `ArrayList`/a linked list concurrently, and at least one of the threads modifies the list structurally, it *must* be synchronized externally...." – user85421 Oct 23 '19 at 21:59
  • 1
    Even for thread safe lists, adding concurrently implies an unpredictable order, which raises the question why the code is using a `List`… – Holger Oct 24 '19 at 09:13

1 Answers1

3

Regular collections are not thread safe, but there are ways to circunvent that:

You can use CopyOnWriteArrayLists, but they are very expensive to write, you can also create a Syncronized Collection, which are not so expensive to write, and you can also work with Queues, it will depend on what you want to achieve.

Cλstor
  • 445
  • 3
  • 11
  • 3
    "Collections are not thread safe" - Collections in [java.util.concurrent](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/package-summary.html) **are** thread-safe. – Jacob G. Oct 23 '19 at 21:54
  • Similar question https://stackoverflow.com/questions/6045648/which-java-collections-are-synchronizedthread-safe-which-are-not – User_67128 Oct 23 '19 at 21:58