Do I need to synchronize access to a List that is only modified by one thread? Do I need to synchronize access to a List that is only modified by one thread? multithreading multithreading

Do I need to synchronize access to a List that is only modified by one thread?


Any time you have more than one thread accessing the same mutable state (well, almost anytime, there are some exceptions, like when you know the state won't mutate within the other thread's lifetime), you need to take some type of action. In this case, you are mutating the field dataList and you expect another thread to react to this. So, you need to do "something". The most general solution is to use synchronized, and your outline of how to do this is just fine.

If you want to use squeeze maximum performance out of something (which is kind of ridiculous for a GUI problem), or you want to show off your great understanding of concurrency, you can consider more light-weight alternatives that apply to more limited circumstances. In this case, you have only one writer, and the writer is only writing a single reference. For such cases, volatile is sufficient. In this kind of code, I would personally just stick to synchronized because it is less likely to break when you change the code, like perhaps you add another writer thread or something.


If you do not make the list synchronized then you should make the List volatile. This way the reading thread gets the latest copy of the List variable's value.

Here is a good explanation.


The official Java-Documentation points out, that an ArrayList is not synchronized. So you need to synchronize it.

However the documentation also says this applies only if multiple threads access the same list. So in your case it should not be necessary to synchronize it. But if you want to be 100% sure you can synchronize your List with this simple call:

List<data_type> list = Collections.synchronizedList(new ArrayList<data_type>());

...where "data_type" is the type values you want to store.