spring-cloud-commons
spring-cloud-commons copied to clipboard
Thread safety of @ConfigurationProperties beans when refreshing
Describe the bug
We use Spring Cloud Config service and we noticed that from time to time we are getting exceptions like ConcurrentModificationException
when accessing some collection types from the properties. Are @ConfigurationProperties
bean supposed to be thread safe? If not what is the recommended way to make them thread safe?
I think this is a duplicate of an issue in spring cloud commons
https://github.com/spring-cloud/spring-cloud-config/issues/1562 is what I was thinking of. @RefreshScope
makes things atomic. There never was a guarantee of thread safety refreshing @ConfigurationProperties
. In the above issue, you can also respond to events specifically.
I don't need consistency/thread-safety across multiple @ConfigurationProperties
beans (which the referenced issue is about if I understand correctly). I only need it internally for a single @ConfigurationProperties
bean.
@RefreshScope makes things atomic
Does this mean if I create my class the following way it will be thread-safe?
So reading the list we will never end up with a ConcurrentModificationException
and we will always see a fully initialized version?
@Component
@RefreshScope
@ConfigurationProperties(prefix = "some-configuration")
public class SomeConfigurationWrapper
{
private List<ConfigurationItem> configurationItems;
public List<ConfigurationItem> getConfigurationItems()
{
return configurationItems;
}
public void setConfigurationItems(List<ConfigurationItem> configurationItems)
{
this.configurationItems = configurationItems;
}
}
Refresh scope means that the next time the bean is created after a refresh, a new instance is constructed