简体   繁体   English

将对象添加到会话线程安全

[英]Adding object to session thread safe

Is the adding object to session threadsafe? 会话线程安全的添加对象是否安全?

in my jsp file, i am checking if session doesn't contain my object then i fetch if from the DB and put it in session. 在我的jsp文件中,我正在检查会话是否不包含我的对象,然后从数据库中获取并放入会话中。

Is this operation thread safe(in case multiple requests get to same line of code at the same time)? 这个操作线程是否安全(如果多个请求同时到达同一行代码)?

The access to HttpSession attributes is not thread safe. 访问HttpSession属性不是线程安全的。 Multiple servlets executing request threads may have active access to the same session object at the same time. 执行请求线程的多个servlet可以同时主动访问同一会话对象。

The Developer has the responsibility for threadsafe access to the attribute objects themselves. 开发人员负责对属性对象本身进行线程安全访问。 You can synchronize on the session object to get/set attributes to it: 您可以在session对象上进行同步以获取/设置其属性:

HttpSession session=request.getSession();
synchronized(session)
{
//get/set attributes to session object
} 

Even though there is a single session (for a user or connectivity) based on the sessionId, any number of concurrent requests can be initiated from that user within a given session. 即使有一个基于sessionId的会话(用于用户或连接),也可以在给定会话中从该用户发起任意数量的并发请求。 For example, a user may be loading this same JSP file that you have written code to add an object from DB to session. 例如,用户可能正在加载您编写的同一JSP文件,以将对象从DB添加到会话中。

Following is an example code to denote what you might be writing. 以下是示例代码,表示您可能正在编写的内容。

object = session.getAttribute("key");
if (object == null) {
   object = getObjectFromDB();
   session.setAttribute("key", object);
}

Since thread switching can happen at any line of the above code segment, there is a possibility that multiple threads noticing the object as null and trying to put the object into session. 由于线程切换可以发生在上述代码段的任何行上,因此有多个线程可能会注意到该objectnull并尝试将其置于会话中。 Since each invocation of session.setAttribute(key,value) with the same key overrides the existing value, there will not be an error thrown. 由于每次使用相同键调用session.setAttribute(key,value)覆盖现有值,因此不会引发错误。

However you will have to consider your business requirement and see whether invoking getObjectFromDB() multiple times unnecessarily is causing issues to the business expectations. 但是,您将必须考虑您的业务需求,并查看是否多次不必要地调用getObjectFromDB()会导致业务预期问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM