Monday 24 October 2016

How to make ArrayList synchronized ?


ArrayList methods are non-synchronized but still if there is a need that we can make them synchronized as :
//Use Collecions.synzhonizedList method
List l = Collections.synchronizedList(new ArrayList());
...

//If you want to use iterator on the synchronized list, use it
//like this. It should be in synchronized block.
synchronized (l) {
  Iterator it = l.iterator();
  while (it.hasNext())
      ...
      it.next();
      ...

}

No comments:

Post a Comment