Reputation: 5938
My question is on threadsafe on Spring controller(finally Servlet class).
1) If i define a varibale static final int i =0, will it cause threadsafe issue, but, I have declared static and final 2) What about declaring enum as global variable like protected enum Mytype{start, stop}? 3)decalring @Autowired is threadsafe?
I have foumd a good article on this, but I need more clarity on above questions. Refer
Code:
@Controller
Public class Test{
@Autowired MyTest mt; // Autowired, thread safe?
private final String s = "abc"; // final, threadsafe?
private static final int i =0; // again final threadsafe?
private static int x = 0; // only static threadsafe?
protected enum Mytype{head, tail}; // enum, threadsafe?
.....
}
Upvotes: 0
Views: 635
Reputation: 5547
This is not so much a Spring question and more a general multi-threading question. Nothing you've asked is specific to Spring with the exception that we can assume that the Controller is an eagerly instantiated Singleton (which means that there is effectively no difference between static and non-static variables in this case). Also, @Autowired has nothing to do with thread-safety. In your example that is simply a non-final package-private field (since that is the default).
With that being said, any final variable which references an immutable object (like a String) or a primitive is innately thread safe because it cannot change.
If multiple threads can access a variable, and that variable's value can be changed, then it is not thread safe unless there is some form of synchronization happening.
Upvotes: 3