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

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

Which Java Collections are synchronized, which are not?

Example: HashSet is not synchronized

10条回答
  •  没有蜡笔的小新
    2020-12-16 12:03

    The previous example is totally wrong.

    First of all, you are not accessing from different threads the list that you just synchronized, you have no prove that the synchronization is being performed properly, you cannot prove that the add process is atomic. Second the synchronized clause over the list itself is a bad practice, you don't know if the optimizer will use an item in the list to do the synchronization, leading to an unexpected behavior. Also, what you're synchronizing is the access to the elements in the list read/write, not the list itself. Take out the Collections.synchronized and see the output. Try many times. Please take following example:

    class ProcessSomething {
        private List integerList = Collections.synchronizedList(new ArrayList<>());
        private void calculate() {
            for (int i = 0; i < 10000; i++) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
                }
                integerList.add(new Random().nextInt(100));
            }
        }
        private void calculate2() {
            for (int i = 0; i < 10000; i++) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
                }
                integerList.add(new Random().nextInt(100));
            }
        }
        public void process() {
            Long start = System.currentTimeMillis();
            Thread t1 = new Thread(new Runnable() {
                public void run() {
                    calculate();
                }
            });
            t1.start();
            Thread t2 = new Thread(new Runnable() {
                public void run() {
                    calculate2();
                }
            });
            t2.start();
            try {
                t1.join();
                t2.join();
            } catch (InterruptedException ex) {
                Logger.getLogger(ProcessSomething.class.getName()).log(Level.SEVERE, null, ex);
            }
            Long end = System.currentTimeMillis();
            System.out.println("Duration: " + (end - start));
            System.out.println("List size: " + integerList.size());
        }
    }
    public class App {
        public static void main(String[] args) {
            new ProcessSomething().process();
        }
    }
    

提交回复
热议问题