java内省优化工具类BeanUtils(优化内省并防止内存泄漏)

java内省(Introspector)
java内省优化工具类BeanUtils(优化内省并防止内存泄漏)

Spring中专门提供了用于缓存JavaBean的PropertyDescriptor描述信息的类——CachedIntrospectionResults。但它的forClass()(获取对象)访问权限时default,不能被应用代码直接使用。但是可以通过org.springframework.beans.BeanUtils工具类来使用。

@Nullable  
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName)  
        throws BeansException {  
    //工厂模式,获取到对应的CachedIntrospectionResults 对象
    CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz);  
    return cr.getPropertyDescriptor(propertyName);  
}  

CachedIntrospectionResults这个类使用的是工厂模式,通过forClass()方法获取到不同的CachedIntrospectionResults对象。

实际上使用的是ConcurrentHashMap进行存储,key就是Class对象,而value是CachedIntrospectionResults对象。

1. CachedIntrospectionResults基本结构

CachedIntrospectionResults对象.png

当使用JavaBean的内省时,使用Introspector,jdk会自动缓存内省信息(BeanInfo),这一点是可以理解的,毕竟内省通过反射的代价是高昂的。当ClassLoader关闭时,Introspector的缓存持有BeanInfo的信息,而BeanInfo持有Class的强引用,这会导致ClassLoader和它引用的Class等对象不能被回收。

获取CachedIntrospectionResults的工厂方法:

static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {  
    //缓存中取
    CachedIntrospectionResults results = strongClassCache.get(beanClass);  
    if (results != null) {  
        return results;  
    }  
    results = softClassCache.get(beanClass);  
    if (results != null) {  
        return results;  
    }  
    //开始创建出CachedIntrospectionResults对象
    results = new CachedIntrospectionResults(beanClass);  
    ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;  
    //确保Spring框架的jar包和应用类的jar包使用的是同一个ClassLoader加载的,这样的话,会允许随着Spring容器的生命周期来清除缓存。
    //当然若是多类加载器的应用,判断应用类使用的类加载器是否是安全的。使得类加载器过期时,能即时清除缓存中的值。
    if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) ||  
            isClassLoaderAccepted(beanClass.getClassLoader())) {  
        classCacheToUse = strongClassCache;  
    }  
    else {  
        if (logger.isDebugEnabled()) {  
            logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");  
        }  
        classCacheToUse = softClassCache;  
    }  
  
    CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);  
    return (existing != null ? existing : results);  
}  

请注意CachedIntrospectionResults使用的是两个缓存。

/** 
 * Map keyed by Class containing CachedIntrospectionResults, strongly held. 
 * This variant is being used for cache-safe bean classes. 
 */  
static final ConcurrentMap<Class<?>, CachedIntrospectionResults> strongClassCache =  
        new ConcurrentHashMap<>(64);  
  
/** 
 * Map keyed by Class containing CachedIntrospectionResults, softly held. 
 * This variant is being used for non-cache-safe bean classes. 
 */  
static final ConcurrentMap<Class<?>, CachedIntrospectionResults> softClassCache =  
        new ConcurrentReferenceHashMap<>(64);  
  • 若应用类和Spring容器类使用的是一个类加载器 || 应用类使用的加载器是用户提前缓存的类加载器,那么存入strongClassCache对象中。
  • 若应用类加载器不是用户提前缓存的类加载器,那么存入softClassCache对象中,即不安全的类加载器。

其实CachedIntrospectionResults对内省的优化一个是缓存PropertyDescriptor对象,第二点就是若类加载器失效时,清除旧缓存。

2. CachedIntrospectionResults防止内存泄漏

清除给定类加载器的内省缓存,删除该类加载器下所有类的内省结果。以及从acceptedClassLoaders列表中移除类加载器(及其子类)。

//源码:org.springframework.beans.CachedIntrospectionResults#clearClassLoader清除缓存和类加载器
public static void clearClassLoader(@Nullable ClassLoader classLoader) {  
    acceptedClassLoaders.removeIf(registeredLoader ->  
            isUnderneathClassLoader(registeredLoader, classLoader));  
    strongClassCache.keySet().removeIf(beanClass ->  
            isUnderneathClassLoader(beanClass.getClassLoader(), classLoader));  
    softClassCache.keySet().removeIf(beanClass ->  
            isUnderneathClassLoader(beanClass.getClassLoader(), classLoader));  
}  

这个方法被谁调用呢?

清除方法调用者.png

这个清除方法的调用者实际上就存在两处:

  1. Spring初始化时org.springframework.context.support.AbstractApplicationContext#refresh
@Override  
public void refresh() throws BeansException, IllegalStateException {  
    synchronized (this.startupShutdownMonitor) {  
       ...
  
        try {  
          //初始化Spring容器
          ...
        }  
  
        catch (BeansException ex) {  
         ...
        }  
  
        finally {  
            // Reset common introspection caches in Spring's core, since we  
            // might not ever need metadata for singleton beans anymore...  
            resetCommonCaches();  
        }  
    }  
}  

在容器初始化时,会重置introspection 缓存,因为可能不再需要单例bean的元数据。

  1. Servlet监听中使用
public class IntrospectorCleanupListener implements ServletContextListener {
    //web 容器初始化时(在filter、servlets初始化之前)执行
    @Override
    public void contextInitialized(ServletContextEvent event) {
        CachedIntrospectionResults.acceptClassLoader(Thread.currentThread().getContextClassLoader());
    }
    //在ServletContext销毁时(filters和servlets销毁执之后)执行
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        CachedIntrospectionResults.clearClassLoader(Thread.currentThread().getContextClassLoader());
        Introspector.flushCaches();
    }
}

IntrospectorCleanupListener实现了ServletContextListener接口。虽然使用Spring本身时不需要使用该监听器,因为Spring自己的内部机制会清空对应的缓存。但是如果Spring配合其他框架使用,而其他框架存在这个问题时,例如Struts 和Quartz,那就需要配置这个监听器,在销毁ServletContext的时候清除对应缓存。

需要注意,即使存在一个Introspector造成内存泄漏也会导致整个应用的类加载器不会被垃圾回收器回收,可能会造成内存泄漏。

配置IntrospectorCleanupListener

@Configuration
public class ServletListenerInfo {
    @Bean
    public ServletListenerRegistrationBean<IntrospectorCleanupListener> IntrospectorCleanupListener() {
        ServletListenerRegistrationBean<IntrospectorCleanupListener> li = new ServletListenerRegistrationBean<>();
        li.setOrder(0);
        li.setListener(new IntrospectorCleanupListener());
        return li;
    }
}

需要注意的是:IntrospectorCleanupListener优先级应该最高。那么它的contextDestroyed方法将会最后一个执行,将会发挥最有效缓存清除的作用。

推荐阅读

加入ehchace后,系统出现内存泄露问题,详细解决方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355