0

I do some initialization in Spring singleton bean @PostConstruct method (simplified code):

@Component
public class Env {
    public String currentEnv;

    @PostConstruct
    public void init() {
        currentEnv = "dev";
    }
}

Should I worry about currentEnv visibility to other beans(other thread) and mark it volatile.

Jeremy Xu
  • 23
  • 5

2 Answers2

0

No, I think it is not necessity.

Only one bean is responsible to initialize the variables and registered it in spring context. So the visibility is guaranteed.

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-postconstruct-and-predestroy-annotations

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html

Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11
  • ```one bean``` ? or are you referring to one thread – zysaaa Dec 10 '21 at 03:48
  • one bean and 1 thread, i don't see any document mention that spring use multiple threads to initialize variables ... – Huy Nguyen Dec 10 '21 at 04:39
  • From the specification in the JLS section 17.4.5:A call to start() on a thread happens-before any actions in the started thread.Because Spring beans are initialized in main thread,so other threads started in the main thread will see complete spring bean.Is this understanding correct?https://stackoverflow.com/questions/49742762/spring-instance-variable-visibility-in-new-thread-started-from-postconstruct – Jeremy Xu Dec 14 '21 at 07:21
  • yes, it's correct. – Huy Nguyen Dec 14 '21 at 07:41
-1

By default, a Spring-managed Bean defined with @Component is a Singleton. This means that if you inject Env into another Spring-managed Bean and given that currentEnv is public, this other Bean could access it.

I would suggest making currentEnv private and creating a getter for the property instead:

@Component
public class Env {
    private String currentEnv;

    @PostConstruct
    public void init() {
        currentEnv = "dev";
    }

    public String getCurrentEnv() {
        return currentEnv;
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
  • I mean other bean can always see the latest "dev" value of currentEnv instead of the stale null when currentEnv not declared as volatile?@João Dias – Jeremy Xu Dec 10 '21 at 15:26
  • Yes. But you should consider making `currentEnv` private and create a getter for the property instead. – João Dias Dec 10 '21 at 16:28