使用@RefreshScope刷新配置属性的线程安全性

huangapple 未分类评论44阅读模式
英文:

Thread safety of refreshing configuration properties using @RefreshScope

问题

我有一个使用@ConfigurationProperties注解的Bean,其中包含应用程序所需的属性。我还使用@RefreshScope注解了该类,以便在运行时刷新任何更改的配置属性。

一个基本版本如下所示:

@Component
@RefreshScope
@ConfigurationProperties
public class ServiceProperties {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    } 
}

getName()方法将被不同的线程不断调用。

我查看了Spring的这份文档:https://cloud.spring.io/spring-cloud-static/Greenwich.SR2/single/spring-cloud.html#refresh-scope

"刷新范围Bean是懒代理,在使用时初始化(即在调用方法时),范围充当初始化值的缓存。要强制Bean在下一次方法调用时重新初始化,必须使其缓存项无效。

RefreshScope是上下文中的一个Bean,并具有用于通过清除目标缓存来刷新范围内所有Bean的公共refreshAll()方法。/refresh端点公开了此功能(通过HTTP或JMX)。要通过名称刷新单个Bean,还有一个refresh(String)方法。"

我从上述文档中的理解是,在调用刷新(通过执行器/actuator/refresh或其他方式)时,Bean会被重新创建和重新初始化。

我的问题是:整个过程是否线程安全?在Bean刷新过程中是否采取了措施以确保在上述类中访问name属性的线程之间不会发生竞态条件?我没有在Spring的官方文档中找到明确的说明。

英文:

I have a bean annotated with @ConfigurationProperties where I have the needed properties by the application bound. I have also annotated the class with @RefreshScope so I can refresh any config properties that change at runtime.

A basic version looks like this:

@Component
@RefreshScope
@ConfigurationProperties
public class ServiceProperties {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    } 
}

The getName() method will constantly be called by different threads.

I had a look at this documentation from Spring: https://cloud.spring.io/spring-cloud-static/Greenwich.SR2/single/spring-cloud.html#refresh-scope

>"Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.

>The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method."

My understanding from the above documentation is that on a call to refresh (through an actuator /actuator/refresh or other means) the bean is re-created and initialized again.

My question is: Is this whole process thread safe? Is care taken to ensure during this bean refresh process that there will not be any race condition among threads trying to access the name attribute in the class above. I did not find any explicit documentation from Spring on this.

huangapple
  • 本文由 发表于 2020年7月26日 23:03:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/63101858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定