简体   繁体   中英

Why bean definitions is stored in concurrent hashmap?

In the class DefaultListableBeanFactory there is

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

where bean definitions are stored. I'm new to Spring and I don't understand why IoC container need concurrency for the hashmap. As far as I understand, we just read bean definitions from XML file and store them in hashmap.

Why don't we use regular HashMap for the purpose?

This is because the bean creation could happen in parallel. The Map is hence going to be critical data. And hence, if there is any update to same key it's done in serial mode and not parallel.

That's why ConcurrentHashMap is used. Now another question who would be registering the beans in parallel. So, it could be any user of DefaultListableBeanFactory . So to make all the operations on beanDefinitionMap thread safe ConcurrentHashMap has been used.

Let's understand it by example:-

 private final DefaultListableBeanFactory factory = (DefaultListableBeanFactory) applicationContext
        .getAutowireCapableBeanFactory();

private void registerBean(String beanName, String scope) throws IOException {

    GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
    genericBeanDefinition.setBeanClassName("org.jibeframework.core.util.ViewComponentFactory");
    genericBeanDefinition.setScope(scope);
    genericBeanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_NO);
    genericBeanDefinition.setDependencyCheck(AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
    BeanDefinitionHolder holder = new BeanDefinitionHolder(genericBeanDefinition, beanName, new String[] {});
    BeanDefinitionReaderUtils.registerBeanDefinition(holder, factory);

}

Now if this code is called inside a Thread could lead to data inconsistency, race conditions etc. That's why all methods inside DefaultListableBeanFactory also acquire different locks( together with using ConcurrentHashMap ) while performing operations like registerBeanDefinition .

Take a look at DefaultListableBeanFactory#registerBeanDefinition to get more clarity. A ref link here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM