If you write in one thread and read in another, the Java Array list is synchronized

If you write in one thread and read in another, the Java Array list is synchronized … here is a solution to the problem.

If you write in one thread and read in another, the Java Array list is synchronized

I have a Controller class running in thread A that makes up a list of local variables like this

Thread A

list = new ArrayList<Map<String, Order>>();
list.add(...);
list.add(...);

where Order is a Java bean with several primitive properties such as String, Int, Long, and so on.

Once the list is built, its reference is passed to the UI thread of the activity (thread B) and accessed there. Cross-thread communication is done using the Handler class + post() method.

So the question is, can I access the list data from thread B completely out of synchronization? Note that once constructed in thread A, the list will not be accessed/modified. It exists as if it were a local variable and then passed to thread B.

Solution

It’s safe. Synchronization completed in a message queue establishes a relationship that occurs first. This assumes, of course, that you don’t modify the map later either. In addition, any objects contained in the map, etc., must not be modified by other threads without proper synchronization.

In short, if neither the list nor any of its data has been modified by a thread other than B, no further synchronization is required.

Related Problems and Solutions