简体   繁体   English

Spring 豆场线程安全

[英]Spring bean field thread safety

I have created a spring library in which there is a scheduler that fetches the configurations from config-server and injects it into fields of a bean.我创建了一个 spring 库,其中有一个调度程序从 config-server 获取配置并将其注入到 bean 的字段中。 Refer diagram below:参考下图:

在此处输入图像描述

The problem is, under heavy load, there might occur thread concurrency issue.问题是,在重负载下,可能会出现线程并发问题。 How should I prevent that?我应该如何防止这种情况?

Some code:一些代码:

This is how a user will give a config key这是用户提供配置密钥的方式

    @AutoConfig("user")
data class ConfigurationWithPrefix (

    @ConfigValue("role")
    val role: String = ""
)

@AutoConfig
data class ConfigurationWithoutPrefix (

    @ConfigValue("user.role")
    val role: String = ""
)

@AutoConfig annotation will make this class a bean. @AutoConfig注释将使这个 class 成为一个 bean。 Then I fetch the bean by @AutoConfig annotation and inserts the value in the @ConfigValue key.然后我通过@AutoConfig注释获取 bean 并将值插入到@ConfigValue键中。


field.set(
          bean,
          valueFromConfig
 )

This process has occurred on a different thread, so while inserting field value if my code tried to access the field concurrency issue will be there, how to prevent it?这个过程发生在不同的线程上,所以在插入字段值时如果我的代码试图访问字段并发问题会出现,如何防止它?

This is similar to cache read/write with multiple threads, for this kind of problem AtomicReference works better that has semantics similar to volatile without synchronization.这类似于多线程缓存读/写,因为这种问题 AtomicReference 工作得更好,其语义类似于 volatile 没有同步。

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

Bean definitions can be converted to: Bean 定义可以转换为:

data class ConfigurationWithPrefix (

    @ConfigValue("role")
    val role: AtomicReference<String> = AtomicReference("")
)

@AutoConfig
data class ConfigurationWithoutPrefix (

    @ConfigValue("user.role")
    val role: AtomicReference<String> = AtomicReference("")
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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