Is a Servlet-Filter which serializes requests in the same user session ok?

The Servelt specification states that the Web-Application is itself responsible for synchronizing access to HttpSessions. It is from the serversite not possible to prevent multiple threads to access the same HttpSession (i.e. the user could always open a second window, retransmit a form etc). My assumption is that while this does not happen often it can happen and therefore I think each access to the HttpSession must be synchronized. For a further discussion see http://forum.java.sun.com/thread.jsp?forum=4&thread=169872 .
Concurrent programming is generally complicated and errorprone. At least in developing JSPs it is inconvenient and easy to forget. My Web-App uses often HttpSession and it can be used in different not predefined places, so I had the idea to implement a ServletFilter which serializes threads which happen in the same session. This involves certainly some overhead. However for the advantages of easier code maintains and higher consistency I am ready to pay this overhead.
My question is generally what you think of this approach and second whether the way I implemented the Filter works.
The Filter actually generates for each Request an HttpServletRequestWrapper which intercepts calls to getSession and on call aquires a Lock so that other threads have to wait for the same Session. The lock is released when the doFilter method of the Filter returns. So threads run concurrently until the first access to the Session and from there they are serialized until the end of the Request.
For the details I will give the code for the Filter and the Wrapper (that?s all the code needed except the ReentrantLock which is Doug Lea?s implementation http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html )
the Filter
public class SessionThreadFilter implements Filter
  public static final String MUTEXT_IN_SESSION_KEY = "org.jaul.filter.SessionThreadFilter.MUTEX";
  //constructor, init, destroy methods do nothing
  public void doFilter(ServletRequest reqIn,ServletResponse res,FilterChain filterChain)
    throws IOException, ServletException
    //if req not instanceof of HttpRequest don't do anything
    if (!(reqIn instanceof HttpServletRequest))
      filterChain.doFilter(reqIn, res);
    } else
      HttpServletRequest req = (HttpServletRequest) reqIn;
      //We use a HttpRequestWrapper each time a user accesses
      //through this
      //Wrapper a Session is Lock is aquired. The filter method returns
      //the lock if it exists is released
      //each thread needs it's own wrapper so the wrapper itself
      //doesn't have to be synchronized
      SessionThreadRequestWrapper wrapper = new SessionThreadRequestWrapper(req);
      try{
        filterChain.doFilter(wrapper, res);
      }finally{
        ReentrantLock lock = wrapper.getLock();
        if (lock != null && lock.holds() != 0)
                   lock.release(lock.holds());
the Wrapper
final public class SessionThreadRequestWrapper extends HttpServletRequestWrapper {
  private ReentrantLock lock = null;
   * Constructor for SessionThreadRequestWrapper.
   * @param arg0
  public SessionThreadRequestWrapper(HttpServletRequest req){
    super(req);
   * @see javax.servlet.http.HttpServletRequest#getSession()
  public HttpSession getSession(){
    return getSession(true);
   * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
  public HttpSession getSession(boolean construct){
    //this will get the session an the lock
    HttpSession session = getLockFromSession(construct);
    if (session == null) return null;
    //get a lock on the mutex
    try{
      lock.acquire();
    } catch (InterruptedException e){
      throw new IllegalStateException("Interrupted while thread waiting for session");
    //now we check again if the session is still valid
    try{
      session.getAttribute(SessionThreadFilter.MUTEXT_IN_SESSION_KEY);
    } catch (IllegalStateException e){
      //again we go recusively but first release the lock
      lock.release();
      lock = null;
      return getSession(construct);
    //after you got the lock you can return the session
    return session;
   * gets the lock from the session
   * @param construct
   * @return HttpSession
  private HttpSession getLockFromSession(boolean construct){
    //test if it is a new Session
    HttpSession session = super.getSession(construct);
    //if is null no session was realy requested
    if (session == null) return null;
    //otherwise try to get the lock if necessery construct it
    //syncrhonized over session
    synchronized (session){
      //this migth throw an Exception if the session has been
      //invalidated in the mean time
      try{
        lock = (ReentrantLock) session.getAttribute(SessionThreadFilter.MUTEXT_IN_SESSION_KEY);
        if (lock == null){
          lock = new ReentrantLock();
          session.setAttribute (SessionThreadFilter.MUTEXT_IN_SESSION_KEY, lock);
        return session;
      } catch (IllegalStateException e){
        //the session has been invalidated before we tried to get the
        //lock we recursively call getLockFromSession
        //( assumption checked with Jetty: if the session is invalidated
        //and getSession is called on the thread a new valid session
        // should is returend)
        //I hope sometime you should get a valid session but I am not
        //sure. This is crucial for breaking of the recursion
        lock = null;
        return this.getLockFromSession(construct);
  /** used by the Filter to get the lock so that it can release it
  ReentrantLock getLock(){
     return this.lock;
}As stated I would be very thankful if you could check the code and give some commends.

synchronized (session){Are you sure that the session instance returned by two
concurrent calls to getSession(...) are the same? I
think that tomcat for instance may return different
instances for the same "logical " session, which would
break your scheme I think... Thank you (I did not know that on Tomcat). The same thing could also occur if another filter wrapped the Session.
That's indeed a problem,which I have already adressed in another thread, but did not get an answer. ( http://forum.java.sun.com/thread.jsp?forum=33&thread=412380). The already cited thread http://forum.java.sun.com/thread.jsp?forum=4&thread=169872 adresses the same problem, but the discussion there ends with the recomandation that you should synchronize on HttpSession as I did it. Also in other forums I've read so.
However like you I've at least strong doubts in this approach, so now my question is on what should I than generally for any access in any web-app syncrhonize the access to Http-Session as demanded by the Servlet specs.
A few not realy satisfying answers:
Synchronize on the HttpSession itself: I think still the best approach, but as you say is it guaranteed that the same instance of an HttpSession is given to each Request (in one Session)?
Synchronized on the HttpServlet: This only works if no other servlet (or jsp) accesses in the session the value with the same key ( of course only if the session itself is threadsave). In case of ThingleThread it is not possible at all there can be multiple instances (you could use a static variable)
Holding the object to synchronize on in applicaton scope or session scope: This obiously doesn't help, because somehow you have to obtain the lock and at least there you need another synchronize.Holding in application socpe is slow a static variable lock would be better there.
Synchronize on some static variable: This will work, but is very slow (each request not only in the same session would synchronize on this).
Hold a map in application scope, which holds for each Session-key a lock: Is probably faster than the static variable thing. However the access and the management of the Map (removing of unused locks etc.- Mabe you could use a WeakHashMap to collect the locks for not used keys anymore) is time consuming too and again the map must be accessed syncrhonasly by all requests.
Syncrhonize on the Filter (only in my case): This is as slow as the static variable approach because each request will use the same lock the one instance of the Filter.
So synchronizing on the session is propably the best approach if the same attribute name is accesed by different servlets. However if you say that some Web-Containers return different HttpSession instances for the same Session (which is legal according to the specification) this of course does not work.
So I have realy no clue on what to syncrhonize than. Now help is not only neede on my Thread serialization filter but on my generally Servlet prgromming.
May be you could help me for another synchronization aproach.

Similar Messages

  • Check-out button is not disable after the check out request from the same user

    HI all,
            I want to use check out/ in procedure in solution manager along with email notification. For that, I have maintained required settings and maintenance project for the intended solution. I want to implement a team leader- manger hiearchy for any changes to the solution. When a team member requests for the check out for any process scenario/ step, the status goes to check out requested. But, the problem is, check-out button is not disable and same user can do the check out which I want to restrict. The check out can be done only by the project manger. I guess, this is related to authorization roles for both team member and manger. But I am not able to find out. Please help me to have the authorization roles for this.
    Thanks,
    Rutvik Upadhyay.

    Why not putting a af:fileDownloadActionListener inside the command button. In the bean you need an method like
        public void exportExcel(FacesContext aFacesContext, OutputStream aOutputStream)
    } You can use the output stream and when you finished just flush it. Don't close the stream and don't complete the response.
    Timo

  • Does af:commandButton submit multiple requests at the same time?

    Hi experts,
    I have a question about af:commandButton behavior.
    I have two commandButtons in a page. They are button1 and button2.
    Button1 takes a few seconds to complete its request process.
    So when I click button1, I can click button2 although button1 request is still being processed.
    I checked how ADF faces handled this situation with servlet filter.
    And I saw that button2 request was always submitted after button1 request was completed.
    Due to this behavior, I would assume that commandButton is designed not to submit multiple requests at the same time and guarantees click order.
    However I couldn't found any documents specifying this feature of commandButton.
    If anyone knows it, could you share?
    I know ADF Faces has busyStateListener to prevent user inputs during request round trip.
    But I'd like to make it sure that I don't need to use busyStateListener if I just want to keep processing order.
    Regards,
    Atsushi

    Hi,
    Does anyone know the document specifying the behavior of af:commandButton in case I click two buttons in a page almost simultaneously?
    Any help will be much appreciated.
    Thanks in advance,
    Atsushi

  • Angular app localhost:9000, all broswers except FF works. get error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource a

    Hello dear mozilla team,
    recently I faced with problem developing angular app with firefox.
    I have an angular app and locally run with grunt which starts on port 9000.
    The application send oauth authorization request on a server which is not on my local, in other words CROSS request
    For all browsers (Safari, Maxthon, Chrome) it opens pages without any error on firefox it is blank page with few error in console.
    I re-installed firefox, delete all add-ons, re-create profile nothing help me.
    here the errors from console.
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at my-server.com
    The connection to ws://localhost:35729/livereload was interrupted while the page was loading.
    I would be very happy if you can help me, as FF is my beloved browser for all inspect and test staff
    Attached please find console screen shot

    Websockets don't use CORS since you're always talking to a different origin by definition (even on the same host it's a different port).
    What version of the browser are you really using? That error message doesn't look like the CORS errors I see in Firefox 36. We changed CORS reporting in Firefox 38 (splitting errors into a dozen different cases) but what you quoted above doesn't match those, either. See [https://bugzilla.mozilla.org/show_bug.cgi?id=1121824 bug 1121824]

  • My laptop was stolen and with it my itunes, all of my music (including non-apple downloaded content) is still on my iphone 5, how can I transfer the files to my new laptop which is authorised to the same apple ID?

    my laptop was stolen and with it my itunes, all of my music (including non-apple downloaded content) is still on my iphone 5, how can I transfer the files to my new laptop which is authorised to the same apple ID?

    See this user tip for recovering the media from the iPhone: https://discussions.apple.com/docs/DOC-3991

  • Multiple leave requests on the same day

    We would like to enforce a check so that multiple leave requests of the same type cannot be submitted for the same day on ESS.
    How can this be achieved ? We are on EP 7.0 and ECC 6.0 and are using webdynpro java version of the ESS applications.
    Any configuration available for this or does this require a BADI implementation ?
    Thanks in advance.
    Thank You,
    Raj

    http://wiki.sdn.sap.com/wiki/display/ERPHCM/ValidationsforESSLeaverequest
    read here, it requies a badi implementation only, no config is available!
    You have to call backend exits from the badi of leave request
    Edited by: Siddharth Rajora on Aug 2, 2011 7:48 AM

  • I have an iphone and an ipad (which are connected by the same apple id) i broke the phone and sold it but i didnt get to factory reset it because it was broken, is there any way for me to wipe my iphone from my ipad?

    i have an iphone and an ipad (which are connected by the same apple id) i broke the phone and sold it but i didnt get to factory reset it because it was broken, is there any way for me to wipe my iphone from my ipad?

    Try this:
    Open the "Find my iPhone" app on your iPad, fill in your AppleID and password at the start up screen, and you should see a list of all your devices and their current location, if connected to a Wi-Fi or mobile data network. Devices not connected will be shown as "offline". But you can still trap on the icon and hit "erase iPhone" in the right hand window.
    If your iPhone is not listed, you did not activate this feature during the setup of the phone and it can't be erased remotely.
    If the phone is listed, even as offline, tap on "erase" to send the erase command. The next time your device will be connected to any kind of network, the content will be erased.

  • How to send two request in the same connection with HttpURLConnection?

    As the title, I want to send two or more requests in the same connection with HttpsURLConnection..I wish all requests are in the same session.
    My code is as following:
    package test1;
    //import javax.net.ssl.*;
    import java.net.*;
    import java.io.*;
    public class httptest {
    public httptest() {
    public void test() {
    HttpURLConnection uc = null;
    String urlStr="";
    urlStr="http://172.16.245.151/test/page1.jsp";
    try {
    URL u = new URL(urlStr);
    uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);
    // uc.connect();
    OutputStream out = uc.getOutputStream();
    out.flush();
    out.close();
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    public static void main(String[] args) {
    httptest tt = new httptest();
    tt.test();
    The sample class just can send a request..Now we think of the sentence :uc = (HttpURLConnection) u.openConnection();
    Obviousely, a HttpURLConnection can just have a Object of the Class URL, and the Class URL have no setURL mothed. So I can't use a HttpURLConnection to send two request.
    I just want the HttpURLConnect is the same to IE...Do you understand what I mean?
    Any helps will be appreciated...

    As the title, I want to send two or more requests in the same connection with HttpsURLConnection..I wish all requests are in the same session.
    My code is as following:
    package test1;
    //import javax.net.ssl.*;
    import java.net.*;
    import java.io.*;
    public class httptest {
    public httptest() {
    public void test() {
    HttpURLConnection uc = null;
    String urlStr="";
    urlStr="http://172.16.245.151/test/page1.jsp";
    try {
    URL u = new URL(urlStr);
    uc = (HttpURLConnection) u.openConnection();
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);
    // uc.connect();
    OutputStream out = uc.getOutputStream();
    out.flush();
    out.close();
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    public static void main(String[] args) {
    httptest tt = new httptest();
    tt.test();
    The sample class just can send a request..Now we think of the sentence :uc = (HttpURLConnection) u.openConnection();
    Obviousely, a HttpURLConnection can just have a Object of the Class URL, and the Class URL have no setURL mothed. So I can't use a HttpURLConnection to send two request.
    I just want the HttpURLConnect is the same to IE...Do you understand what I mean?
    Any helps will be appreciated...

  • How do I get the internet connection back onto ipad even though it connects to Wifi successfully and I have checked on my iPhone which does connect via the same wifi and to the internet?

    How do I get the internet connection back onto ipad even though it connects to Wifi successfully and I have checked on my iPhone which does connect via the same wifi and to the internet?

    Your router may not have given your iPod a valid IP address. Go to Settings > Wifi > your network name and touch the ">" to the right to see the network details. If the IP address shown starts with 169 or is blank then your router didn't provide an IP address and you won't be able to access the Internet.
    Sometimes the fix can be as simple as restarting your router (remove power for 30 seconds and restart). Next, reset network settings on your iPod (Settings > General > Reset > Reset network settings) and then attempt to connect. In other cases it might be necessary to update the router's firmware with the latest from the manufacturer's support web pages.
    If you need more help please give more details on your network, i.e., your router make/model, the wifi security being used (WEP, WPA, WPA2), etc.

  • How to compare the transports requests in the same system

    HI ,
    Is there any option to compare transport requests  in the same system whether both contain the same objects or not.

    Ambarish, you can perform check in two ways.
    -you can go to /usr/sap/trans compare the data files and cofiles andcheck the physical size whether it is same or not.
    -you open the TR in SE01 tcode, select the sub TR and expand it it will show you the list of objects/programs included in that TR.
    Hope it addresses your query.
    Regards, Amber S | ITL

  • Is it possible to send several http requests at the same time?

    hi:
    is it possible to send several http requests at the same time in j2me application, or it's device specific.
    It's ok in my NOKIA SYMBIAN C++ application.
    regards
    Message was edited by:
    danielwang

    Is it possible to have 2 threads running at the same
    time at different times eg 1 repeats every 20
    miliseconds and the other 40 for example. Yes.
    http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

  • HT204291 Does mirroring automatically mirror content to other devices which are registered under the same name ? If so does this occur across different distances? Does Apple Tv store mirrored content?

    Does apple tv automatically mirror content from one device to all other iPad or  mackbook devises which are registered under the same name? If so does a device have to be in the same area ?

    Welcome to the Apple Community.
    Mirroring only works FROM a mobile device TO an Apple TV.

  • Why we cannot view the move orders which are created by the other user?

    Hi,
    Can any one explain me the below point.
    Why we cannot view the move orders which are created by the other user.
    Ex: From ABC user I have created a Move Order: 123456 in M1 Org If I login to the other user BCD I cannot view the same move order in the same ORG i..e M1 ORG.
    But we can perform the transact move orders for move orders which is created by the other user.
    What could be the reason? Why the system is restricting this? Is this the standard functionality of oracle?
    Can any one explain?
    Regards,
    Kv.

    This is due to a security function which allows to see the move orders created by the user only.
    Please refer to the meta link document ID 280131.1 for detailed description.
    I have tried these steps in one of my test instances long back and was able to see move orders created by other users.
    Thanks
    Karthik.

  • I have a canon AirPrint printer   an iPad 4 Which are connected to the same wifi connection but will not work any ideas

    I have a canon airprint printer new + an iPad 4 also new which are connected to the same wifi router but the iPad cannot find the printer no matter what I do I can't find the printer ? Any idea's

    You don't mention the router model but some Thompson routers appear to have a problem working with Bonjour/mdns. There's some information here:
    http://blog.hosk.in/2011/01/telecom-nz-thomson-tg585v8-with-apple.html

  • Will customers who purchased an iMac after the 1st October get a refund on iWorks which was purchased at the same time?

    Will customers who purchased an iMac after the 1st October get a refund on iWorks which was purchased at the same time?
    As the titile says. I purchased an iMac on the 4th October and added pages, keynote and numbers to the purchase. Now I find out if I didn't purchase them I would have them free anyway (and to make it more annoying I haven't even used the apps yet so have had no use out of them until this point). I know Apple gave refunds for the same situation on iOS iWorks in September.

    There is an up-to-date program for those who purchased new Macs after October 1.

Maybe you are looking for

  • How to Create Reports Services

    Hi all, <br><br> In Oracle 10 R2 Application Server for Windows 2003, is there a way to create a new Report Server services in the Application Server other than the already existing one? If yes, how? <br><br> Thanks in advance. <br><br> <i>Note:</i>

  • Converting a hex String to its corresponding hex value...?

    Yeah, I'm having quite a bit of fun guessing this one... :p I have a string of n characters and have used Integer.toHexString( ( int )str.charAt( i ) ) to convert each character to a string representing its hex value. Now I need to USE that value for

  • How do you make the down state last a few seconds?

    I have an assignment due next week where you click something and a little text box pops up telling you what that item is. I also made it so the item changes colour. However, right now I've just got it so that you hover your cursor over it, it fades a

  • Problem in net configuration assistant

    Hi,I have loaded oracle 9ienterprise edition on one PC and oracle9i client.when i am running Net configuration assistant to connect to server it gives me error ORA-12535: TNS:operation timed out.i have tried lot of things like reinstalling client,dro

  • Scrolling page doesn't work in "Fit one full page to window" view

    Scrolling page doesn't work in "Fit one full page to window" view it is still not working in V11.0.10 is there a new fix?