Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are autowired objects in spring-mvc threadsafe?

Question 1) From my understanding spring creates singletons objects, So when I have a controller like below with a autowired service, will that affect threadsafety.

Question 2) If I declare a int type variable at class level and use it in controller or service, will it affect thread safety?

@Controller
public class LoginController {

    @Autowired
    public DaoService daoservice;

    @RequestMapping("/")
    public String getBookInfo() {
        Book book = daoservice.getBookbyId(1L);
        System.out.println(book.getTitle());
        return "welcome";
    }
}


@Service
public class DaoService {

    @Autowired
    public BookRepository BookRepo;

    public Book getBookbyId(Long Id) {
        Book book = BookRepo.findOne(Id);
        return book;
    }

}
like image 515
Yashwanth Potu Avatar asked Oct 12 '17 05:10

Yashwanth Potu


People also ask

Are Autowired objects singleton?

By default they're singletons. If the scope is changed to prototype, you get separate objects.

Are spring beans Threadsafe?

Are Spring Beans Thread Safe? No. Spring has different bean scopes (e.g. Prototype, Singleton, etc.) but all these scopes enforce is when the bean is created.

What is the use of @autowired in spring MVC?

Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.

Is Autowired a dependency injection?

Enabling @Autowired AnnotationsThe Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring.


1 Answers

Q.1 : Are Spring Beans Thread Safe?
Answer: No.
Spring don't give you thread safety for their bean. Spring provide different type of bean scope like (Prototype,Singleton etc). If Prototype then a new bean create each time it invoke where a singleton bean created for one time and shared in application context.

If you are thinking for HTTP request, then 2 or more request can come.Hence new instance of a bean is created in each request scope. So you can think they are thread safe in context of HTTP request but it's not truly thread safe by spring itself.Because several thread can share the bean within the same HTTP request context.

Q.2 : Are Class variable Thread Safe?
Answer: No
Quoted from here
All private member variables are shared. They might be final, but that only means that the references can't be changed. Any mutable state must be synchronized.

like image 114
Ataur Rahman Munna Avatar answered Sep 28 '22 07:09

Ataur Rahman Munna