Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an array thread safely in Java?

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?

like image 639
user3692521 Avatar asked Mar 19 '15 19:03

user3692521


3 Answers

You will not get an invalid state when changing arrays using multiple threads. However if a certain thread has edited a value in the array, there is no guarantee that another thread will see the changes. Similar issues occur for non-volatile variables.

like image 76
Dermot Blair Avatar answered Oct 21 '22 03:10

Dermot Blair


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.

like image 43
Razib Avatar answered Oct 21 '22 01:10

Razib


array operations are not threadsafe. you can either lock on a field, i would recommend to add a field e.g. named LOCK and do the

void add(){
 syncronized(LOCK) {
  // add
 }
}

void get(int i){
 synchronized(LOCK){ 
   // return
 }
}

or simply use

java.util.concurrent.*
like image 1
wgitscht Avatar answered Oct 21 '22 01:10

wgitscht