spring-cloud-commons icon indicating copy to clipboard operation
spring-cloud-commons copied to clipboard

Thread safety of @ConfigurationProperties beans when refreshing

Open martin-tarjanyi opened this issue 4 years ago • 4 comments

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?

martin-tarjanyi avatar May 04 '20 07:05 martin-tarjanyi

I think this is a duplicate of an issue in spring cloud commons

spencergibb avatar May 04 '20 13:05 spencergibb

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.

spencergibb avatar May 04 '20 15:05 spencergibb

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;
    }
}

martin-tarjanyi avatar May 04 '20 20:05 martin-tarjanyi

Refresh scope means that the next time the bean is created after a refresh, a new instance is constructed

spencergibb avatar May 04 '20 20:05 spencergibb