Java源码解读-数据容器都是如何实现同步的

用Java的同学可能在自己使用或者面试的时候经常遇到这么一个问题, 哪些数据结构或者容器是同步的, 是怎么实现的同步?

其实很多的数据同步原理都比较简单, 我把目前知道的数据容器的同步方式稍微梳理了一下

1. 线程安全容器

StringBuffer(太明显,synchronized关键字)

    @Override
    public synchronized StringBuffer append(String str) {
        toStringCache = null;
        super.append(str);
        return this;
    }

HashTable(额,一样,synchronized关键字)

public synchronized V put(K key, V value) {
        ...
}

Vector(额, 还是一样,synchronized关键字)

public synchronized boolean add(E e) {
        ...
          
}
ConcurrentHashMap (相对高效,针对某个节点加锁,高端了点点)
 public V put(K key, V value) {
        return putVal(key, value, false);
 }

 final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;
        for (Node[] tab = table;;) {
            Node f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                if (casTabAt(tab, i, null,
                             new Node(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                //看这里,这个叫分片锁
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            binCount = 1;
                            for (Node e = f;; ++binCount) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node pred = e;
                                if ((e = e.next) == null) {
                                    pred.next = new Node(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        else if (f instanceof TreeBin) {
                            Node p;
                            binCount = 2;
                            if ((p = ((TreeBin)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

 CopyOnWriteArrayList (使用ReentrantLock, 进行加锁)

 public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
BlockingQueue 阻塞队列
//数据插入
public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            //超过容量,插入失败
            return false;
        int c = -1;
        Node node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        //数据插入锁,保证数据插入的同步
        putLock.lock();
        try {
            if (count.get() < capacity) {
                enqueue(node);
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }
//数据获取,类pop操作
public E poll() {
        final AtomicInteger count = this.count;
        if (count.get() == 0)
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.takeLock;
        //数据获取锁,防止数据获取异常
        takeLock.lock();
        try {
            if (count.get() > 0) {
                x = dequeue();
                //队列元素减少,AtomicInteger原子操作
                c = count.getAndDecrement();
                if (c > 1)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }

2. 容器同步化

Collections.synchronizedXXX(<数据容器>)

...
final Object mutex;     //用户控制同步的对象锁
//构造方法
SynchronizedCollection(Collection c) {
      this.c = Objects.requireNonNull(c);
      mutex = this;
}
//接上面的操作,看出来没有没?就是以当前容器作为对象锁, 在操作的时候通过锁定对象实现线程安全
...
public boolean add(E e) {
     synchronized (mutex) {return c.add(e);}
}
public boolean remove(Object o) {
     synchronized (mutex) {return c.remove(o);}
}
...

关于线程部分的代码目前还没看到,后续补上

你们还知道哪些数据容器的加锁方式, 可以给我评论

未完,有机会再续

你可能感兴趣的:(Java开发,Java源码解读,数据容器,同步机制)