1

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.

4

2 回答 2

1

线程安全涉及线程之间共享的数据。例如,在您的情况下,如果您获得了当前用户并希望将其存储在一组 todaysUsers 中,那么您必须保护对该组的数据访问:

private static Set<Integer> todaysUsers = new HashSet<Integer>();

public static Integer getCurrentLoggedInUserId(HttpSession session)
{
    Integer currentUser = ......
    synchronized(todaysUsers) {
         todaysUsers.add(currentUser);
    }
    return currentUser;
}

因为每个线程都会使用自己的会话调用该方法,所以这不是数据共享,因此对线程安全没有问题

于 2013-09-09T07:23:57.053 回答
0

是的。Util如果类没有状态,这将是线程安全的。

通常不会这样做,因为理想情况下只有 Servlet 应该知道请求/响应对象。

如果您正在编写一个专门作用于请求/响应对象的实用程序类,请考虑编写一个包装类来包装请求对象,然后对其进行操作。

这样,您在为每个请求创建新包装器时就不会担心线程安全问题。

于 2013-09-09T07:20:07.723 回答