Using request.getSession() as a locking object?

后端 未结 7 975
面向向阳花
面向向阳花 2020-12-11 02:18

I have some java code that gets and sets a session attribute:

Object obj = session.getAttribute(TEST_ATTR);
if (obj==null) {
  obj = new MyObject();
  sessio         


        
7条回答
  •  自闭症患者
    2020-12-11 02:56

    In the context of servlets? Servlets can be distributed across multiple processes, therefore you can't always have the same session object. A corollary to this is that a servlet container may decide to give you a different session object in the same process.

    IIRC, Brian Goetz wrote an interesting article on the difficulty of doing things right with sessions.

    My advice: Stay clear of sessions as much as possible, and don't lock random objects (use a lock object that has no other purpose).

提交回复
热议问题