java - In what case it will be not thread-safety -
all, better understanding attributes
of httpsession
thread issue.i wrote test code ,i had thought below code should thread-safety way go.
httpsession session = request.getsession(); synchronized (session) { integer n = (integer) session.getattribute("foo"); session.setattribute("foo", (n == null) ? 1 : n + 1); }
but answer of tell me not . can't understand ,in opinion, thought session conversion between 1 client , server .is there thread issue situation? if there , please tell me in case code not thread-safety. thanks.
afaik, nothing prevents servlet container return different object each time thread asks session (i.e. proxy on real, actual session).
if container that, synchronizing on session won't of help, since each thread synchronize on different object.
the easiest way have thread-safe counter use atomicinteger, , call 1 of increment methods, doesn't prevent 2 concurrent threads storing atomicinteger first time if both see null.
the easiest way sure (although not fastest) use global lock attribute:
public static synchronized atomicinteger getcounterfromsession(httpsession session) { atomicinteger counter = (atomicinteger) session.getattribute("counter"); if (counter == null) { counter = new atomicinteger(); session.setattribute("counter", counter); } return counter; }
that said, in clustered application, session made persistent or replicated across nodes of clustered, doesn't bring guarantee either. storing counter in database solution here.
Comments
Post a Comment