Reputation: 4973
Suppose I have one repeated task which is going to process HttpSession or HttpServletRequest or HttpServletResponse object. This processing may be abstract some data from HttpSession or set/get some attributes in HttpServletRequest/HttpServletResponse.
Here I am giving one example for idea. I want my current logged in UserId from session. for that I am making one Util method in one of Util classes.
public static Integer getCurrentLoggedInUserId(HttpSession session)
{
// here I will process session object and get first User object and
//after that I will get id from that User Object. This is one repeated task in my app.
}
second example for download file.
public static void downloadFile(HttpSrvletResponse response)
{
// here I will set some attribues/parameters in response for download file.
}
Now my question is it thread safety to doing this? I mean is it recommended to pass session/request/response objects from controller/servlets to Util classes? If not, what is solution for these kind of repeated tasks?
Thanks in advance.
Upvotes: 1
Views: 4489
Reputation: 1626
Thread safety concerns data that is shared amongst threads. For example in your case if you obtained the current user and want to store it in a set of todaysUsers, then you must protect data access to that set:
private static Set<Integer> todaysUsers = new HashSet<Integer>();
public static Integer getCurrentLoggedInUserId(HttpSession session)
{
Integer currentUser = ......
synchronized(todaysUsers) {
todaysUsers.add(currentUser);
}
return currentUser;
}
because each thread will call the method with it's own session, this is not data sharing and thus no issue for thread safety
Upvotes: 1
Reputation: 61158
Yes. This would be thread safe if the Util
class has no state.
Usually this isn't done because ideally only the Servlet should know about the request/response objects.
If you are writing a utility class that exclusively acts on the request/response objects consider writing a wrapper class that wraps, say, the request object and then acts on it.
This way you don't have thread safety concerns as you create new wrappers for each request.
Upvotes: 0