Ad

Different Different Threads Modifying Different Indices Of A Shared List

Is it a good design to have X different threads modify X different indices of a list or basically X different threads modifying X different properties of a shared object. I considered using synchronised/synchronisedList(any concurrent datastructure) but I want to avoid the performance overhead that comes with it. Does the approach depend on the value of X?

According to this is multiple threads adding to single arraylist might work but it's not a good design, is it the same with this?

In case the answer varies from language to language, I am asking in particular about JAVA, but would want to know why is it that different languages have this differently.

Ad

Answer

If we assume that your list has a fixed initial size of let's say 10 elements and you have 10 threads manipulating elements 1 to 10 there is no shared mutual state involved (see shared mutual state is the root of all evil). Thus, I see no big problem with synchronization and would go with the list.

But, keep in mind that this heavily depepends on the operations performed and the size of the list. If you have 1000000 elements inside the list, creating 1000000 threads would be inefficient or even impossible.

Also as soon as you start adding and deleting elements from the list, you have the list itself as shared mutual state and you must now worry about synchronization.

Edit: about shared mutual state

If you shared state that is not mutual you cannot have problems with synchronization because nobody can change the data anyway.

If you have mutual state that is not shared you can change the state but nobody except your current code works on the state anyway, thus the change are directly reflected inside your code.

If you have shared mutual state, your can now have two threads were each one can change the data of the other. In multithreading the order in which this changes happen and a reflected by the reader is not deterministic as long as you do not apply mechanisms such as synchronization or locking. Thus, you can have the classical problems like:

  • A reads data from element x and transforms it.
  • B reads data from element x and transforms it <-- A has not written its changes yet, thus B works with outdated data
  • A writes data to element x
  • B writes data to element x <-- A's changes are lost
Ad
source: stackoverflow.com
Ad