In a struts 2 and spring web based application, please consider below sample.
The BookManager
has an action which returns a Map
of books to client. It get the map from service layer which is injected
by Spring
public class BookManager extends ActionSupport {
//with setter and getter
private Map<String, BookVO> books;
@inject
BookService bookservice
@Action("book-form")
public String form(){
setBooks(bookservice.getAllBooks());
}
}
The service layer gets the book list from DB an returns a MAP.
@Named
public class BookService(){
private Map<String,BookVO> books;
public Map<String,BookVO> getAllBooks(){
books = new HashMap<String,BookVO>();
//fill books from DB
return books;
}
}
I have tested and found that the above implementation is not thread safe.
- I can make the code thread safe by removing private field
books
fromBookService
and use it like methodHashMap<String,BookVO>() books = new HashMap<String,BookVO>();
. Why this change make the code thread safe ? - The struts action is thread safe, shouldn't this assure that the even non thread safe spring service runs in a thread safe manner.
- If I use the non thread safe version of service in my action, by making a
new
service object instead of using spring inject, I will face no issue. Why? If the service is not thread safe why making a new instance and calling it will be thread safe!