Are operations on arrays in Java thread safe?
If not how to make access to an array thread safe in Java for both reads and writes?
Operation on array in java is not thread safe. Instead you may use ArrayList with Collections.synchronizedList()
Suppose we are trying to populate a synchronized ArrayList of String. Then you can add item to the list like -
List<String> list =
Collections.synchronizedList(new ArrayList<String>());
//Adding elements to synchronized ArrayList
list.add("Item1");
list.add("Item2");
list.add("Item3");
Then access them from a synchronized block like this -
synchronized(list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
Or you may use a thread safe variant of ArrayList - CopyOnWriteArrayList. A good example can be found here.
Hope it will help.