垃圾回收Spring Bean
Bean 垃圾回收(GC)
-
关闭Spring 容器(应用上下文)
-
执行GC
-
Spring Bean 覆盖的finalize() 方法被回调
结论:
在ApplicationContext关闭之前,GC是不会回收Bean的,纵然显示的调用也是如此。而在ApplicationContext关闭之后,JVM会在垃圾回收周期中去回收掉Bean。
调用close方法就是调用存放bean的concurrentHashMap的clear方法,导致GCRoot不可达,所以就被回收了.
然而有可能外部对象再次引用, 因此这个说法只适用于在 Spring IoC 容器中的对象
代码示例
spring-core项目
搜索 40 | 回收Spring Bean
BeanGarbageCollectionDemo.java
DefaultUserFactory.java
BeanGarbageCollectionDemo.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.geekbang.thinking.in.spring.bean.definition;
import org.geekbang.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 40 | 回收Spring Bean:Spring IoC容器管理的Bean能够被垃圾回收吗?
*
* Bean 垃圾回收(GC)示例
* • Bean 垃圾回收(GC)顺序
* 1. 关闭Spring 容器(应用上下文)
* 2. 执行GC
* 3. Spring Bean 覆盖的finalize() 方法被回调
*
* 在ApplicationContext关闭之前,GC是不会回收Bean的,纵然显示的调用也是如此。
* 而在ApplicationContext关闭之后,JVM会在垃圾回收周期中去回收掉Bean。
* 调用close方法就是调用存放bean的concurrentHashMap的clear方法,导致GCRoot不可达,所以就被回收了.
* 然而有可能外部对象再次引用, 因此这个说法只适用于在 Spring IoC 容器中的对象
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since
*/