跳至主要內容
ConcurrentHashMap

ConcurrentHashMap

ConcurrentHashMap

产生原因:

  • 并发编程中使用HashMap可能导致程序死循环。导致HashMap的Entry链表形成环形数据结构,一旦形成环形数据结构,Entry的next节点永远不为空,就会产生死循环获取Entry。
  • 而使用线程安全的HashTable效率低。HashTable容器使用synchronized来保证线程安全,竞争越激烈效率越低

实现高性能原理

  • ConcurrentHashMap使用分段锁来保证在多线程下的性能。一次锁住一个桶。将hash表分为16个桶,诸如 get,put,remove 等常用操作只锁当前需要用到的桶
  • ConcurrentHashMap使用了一种不同的迭代方式。当 iterator被创建后集合再发生改变就不再是抛出ConcurrentModificationException异常,而是在改变时new新的数据从而不影响原有的数据,iterator完成后再将头指针替换为新的数据 ,这样iterator线程可以使用原来老的数据,而写线程也可以并发的完成改变

HeChuangJun大约 22 分钟源码sourcecode
ReentrantLock

ReentrantLock

ReentrantLock

  • 特点:公平、非公平、可重入、互斥锁、需手动开启和释放锁,异常不自动释放锁,要在finally里面声明。底层使用Unsafe的park方法加锁,
  • 所有方法实现实际上都是调用了其静态内存类Sync中的方法,而Sync类继承了同步器AbstractQueuedSynchronizer(AQS)是关键
    ![](源码-AbstractQueuedSynchronizer.md)
  • volatile保证有序和可见性,cas保证原子性,保证线程同步

HeChuangJun大约 13 分钟源码sourcecode
ReentrantReadWriteLock

ReentrantReadWriteLock

15. ReentrantReadWriteLock

  • 特点:公平、非公平锁、读写锁、重入锁、锁降级

1. 构造方法

public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
    public ReentrantReadWriteLock() {
        this(false);
    }
    public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }
    public static class ReadLock implements Lock, java.io.Serializable{
        private final Sync sync;
        protected ReadLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }
    }
    public static class WriteLock implements Lock, java.io.Serializable{
        private final Sync sync;
        protected WriteLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }
    }
    static final class FairSync extends Sync {
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }
    }
    static final class NonfairSync extends Sync {
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            return apparentlyFirstQueuedIsExclusive();
        }
    }
}

HeChuangJun大约 6 分钟源码sourcecode
Spring

spring源码

1. AnnotationConfigApplicationContext extends GenericApplicationContext,AbstractApplicationContext,DefaultResourceLoader

implements AnnotationConfigRegistry,BeanDefinitionRegistry,ConfigurableApplicationContext,AliasRegistry,ApplicationContext,Lifecycle,Closeable
EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver,BeanFactory,ResourceLoader,AutoCloseable
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry{
private final AnnotatedBeanDefinitionReader reader;


HeChuangJun大约 30 分钟源码sourcecode