Collections同步化容器

2017-07-20  本文已影响19人  远o_O
Collections.synchronizedMap(new HashMap<>());
Collections.synchronizedList(new LinkedList<>());
Collections.synchronizedSet(new TreeSet<>());
    public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
        return new SynchronizedMap<>(m);
    }

    /**
     * @serial include
     */
    private static class SynchronizedMap<K,V>
        implements Map<K,V>, Serializable {
        private static final long serialVersionUID = 1978198479659022715L;

        private final Map<K,V> m;     // Backing Map
        final Object      mutex;        // Object on which to synchronize

        SynchronizedMap(Map<K,V> m) {
            if (m==null)
                throw new NullPointerException();
            this.m = m;
            mutex = this;
        }

        SynchronizedMap(Map<K,V> m, Object mutex) {
            this.m = m;
            this.mutex = mutex;
        }

        public int size() {
            synchronized (mutex) {return m.size();}
        }

应该很清楚了:

由于采用的是加锁实现线程安全,因此相对于CAS,copy on write等无锁实现,效率低下,从而也降低了吞吐率。

上一篇下一篇

猜你喜欢

热点阅读