Which Java Collections are synchronized(thread safe), which are not?

前端 未结 10 2137
礼貌的吻别
礼貌的吻别 2020-12-16 11:05

Which Java Collections are synchronized, which are not?

Example: HashSet is not synchronized

10条回答
  •  忘掉有多难
    2020-12-16 12:04

    synchronize makes performance lower. of course, Java collection is not synchronized. but Java provides a Synchronization Wrappers to synchronize Java Collection see link

    for example:
    
    
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.Iterator;
        import java.util.List;
    
        public class SynchronizedListExample {
    
            public static void main(String[] args) {
    
                List syncList = Collections.synchronizedList(new ArrayList());
    
                syncList.add("one");//no need to synchronize here
                syncList.add("two");
                syncList.add("three");
                String st = syncList.get(0); //it is ok here => no need to synchronize
    
                // when iterating over a synchronized list, we need to synchronize access to the synchronized list
               //because if you don't synchronize here, synchList maybe be changed during iterating over it
                synchronized (syncList) {
                    Iterator iterator = syncList.iterator();
                    while (iterator.hasNext()) {
                        System.out.println("item: " + iterator.next());
                    }
                }
    
            }
    
        }
    

提交回复
热议问题