Online Java Compiler By
JavaTpoint.com
import java.util.*; public class CollectionsSynchronizedCollectionExample3 { public static void main(String[] args) { Collection
obj = new ArrayList<>(); obj.add("JavaTpoint"); // not thread safe Collection
synObj = Collections.synchronizedCollection(obj); synObj.add("SSSIT"); // thread safe //Below iteration will result in non-deterministic behavior Iterator
ite1 = synObj.iterator(); while (ite1.hasNext()) { String s = ite1.next(); System.out.println(s); } //Below code is the right way to iterate synchronized collection synchronized(synObj) { Iterator
ite2 = synObj.iterator(); while (ite2.hasNext()) { String s = ite2.next(); System.out.println(s); } } } }
Output