spring-core-4-40 | 回收Spring Bean:Spring IoC容器管理的Bean能够被垃圾回收吗?

本文探讨了Spring IoC容器管理的Bean何时会被垃圾回收。当ApplicationContext关闭后,Bean才会被JVM回收,并且在垃圾回收周期中清除。调用close方法会清除Bean的引用,但在容器外仍有被引用的可能性。
摘要由CSDN通过智能技术生成

垃圾回收Spring Bean

Bean 垃圾回收(GC)

  1. 关闭Spring 容器(应用上下文)

  2. 执行GC

  3. 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
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值