Is it necessary to synchronize HttpServletRequest object

Is it necessary to synchronize HttpServletRequest object .
Justify your answer
With regards
Aruanbh Dash

i'd say no, because it's supposed to be generated and processed by a single thread of the servlet engine
after that, nobody will arrest you if you torture a request with multithreading

Similar Messages

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • How to get the HttpServletRequest object in a jsp

    Hi,
    I am a little confused here. Am trying to use the HttpServletRequest object in my jsp. I have set up just a simple test page jsp. How can i use the HttpServletRequest object to get some information about the request for example using the method getPathInfo(). I know i can do this in a servlet and pass the value as a parameter in a doGet method. But how do i do it in a jsp. Can it be done..?
    Pls help
    Thankyou

    The request object is already created for you in JSP, as are many other things
    request - the HttpServletRequest object
    response - the HttpServletResponse object
    session - the HttpSession object
    application - the ServletContext object
    out - the JspWriter object (like PrintWriter)
    So you just use them...
    <%
    String asdf = request.getParameter("asdf");
    %>

  • Can I get the HttpServletRequest object in my custom auth providers?

    Hello -
    If I write a custom authentication or identity assertion provider, is there a way to get the HttpServletRequest object of the user's request?
    Thanks,
    -- Scott

    You can do it from your identity asserter in the following way!
    public CallbackHandler assertIdentity(String type, Object token, ContextHandler context) throws IdentityAssertionException
    Object requestValue = context.getValue("com.bea.contextelement.servlet.HttpServletRequest");
    HttpServletRequest request = (HttpServletRequest) requestValue;
    -Faisal
    http://www.weblogic-wonders.com

  • Getting the Client Certificate out of the HttpServletRequest object

    I have an interesting issue with weblogic 5.1 SP6 and getting/obtaining Client
    Certificates.
    The issue is that the Client Certificate is not always in the HttpServletRequest
    object depending on how the weblogic.properties are set. Here is my code to get
    the Certificates.
    // get the cert chain from the request
    Object obj=request.getAttributs("javax.net.ssl.peer_certificates");
    if (obj instanceof weblogic.security.X509[]) {                          
    weblogic.security.X509[] wlogicCert = (weblogic.security.X509[]) obj;
                                            try {
                                            iaik.x509.X509Certificate iaikClientCert =
         new iaik.x509.X509Certificate(wlogicCert[0].getBytes());
         clientSDN = aiaikClientCert.getSubjectDN().getName();
         clientCert = (Certificate)iaikClientCert;
    The only time the certificate is present in the Request Object is when the following
    weblogic.properties are set:
    weblogic.security.enforceClientCert=true
    weblogic.security.clientRootCA=CARoot.pem
    If the properties are set to to this: no Certificate can be received from the
    Request object.
    weblogic.security.enforceClientCert=false
    #weblogic.security.clientRootCA=CARoot.pem
    Is there a way to have Weblogic always receive/get a Client Certificate if one
    is provided by the client, but not have weblogic do any validation of the certificate?
    Any help would be appreciated!
    Gary

    ok i see.
    although it should be able to get the underlying
    outputStream handle since i have initialized
    (associated) it on the previous line.
    ThanksWell, you might be able to get the underlying stream. Look at the API docs. If there's a method there to do it, then you can. If not, then you can't.
    If you can do it, then you have to look at the API docs for FileOutputStream and see if it lets you get the associated File or path. If such a method exists, then you can get it. If not, then you can't.
    Even if both methods exist and you can utimately get the file, do you understand why this is not the same as "getting the file associated with a PrintStream"?

  • Synchronize on objects held in non-final variables?

    [This thread|http://forums.sun.com/thread.jspa?messageID=10775877#10775877] and post got me thinking:
    linuxisbest.eric wrote:
    I have noticed in my textbook that it creates a String in two ways:
    String a = new String("Hello");and
    String a = "Hello";Which one should I use? Is there any practical difference?
    YoungWinston wrote:Pick door number two linux ... unless you plan on synchronizing on it, that is.
    WinstonIs it best practice to only synchronize on objects held in final variables?
    Edited by: Encephalopathic on Jul 26, 2009 5:46 AM

    gnat wrote:
    Is it best practice to only synchronize on objects held in final variables?
    Above [best practices|http://en.wikipedia.org/wiki/Best_practices] apply to cases when lock is not intended to change.
    I think that there could be cases when lock is actually intended to change and therefore shouldn't be final. Here's an example of caching code I've seen recently:
    private final ConcurrentMap<Integer, Object> pendings
    = new ConcurrentHashMap<Integer, Object>();
    public Object loadEntity(int entityId) {
    Object lock = new Object(); // shouldn't be final, see below
    Object prev = pendings.putIfAbsent(entityId, lock);
    if(prev != null) {
    // without using prev lock, there would be a chance
    //  for concurrent threads to perform redundant invocation
    //  of retrieveEntityFromSomewhereSlowly for same entityId
    lock = prev;
    Object res;
    synchronized (lock) {
    res = getEntityFromCacheQuickly(entityId);
    if (res == null) {
    // cache miss - retrieve entity slowly:
    res = retrieveEntityFromSomewhereSlowly(entityId);
    pendings.remove(entityId);
    gnat,
    Huh? Please could you try to talk me through that code... At first glance, I don't follow it... I think it's still got "unprotected race conditions", but after reading it through several times (in the course of trying to frame a post saying basically "I don't think that will work, and here's why" I now think I understand how it does work (almost all the time), but I'd just really really like some validation of my mis/understanding.
    So... Here's how I think that works... please could you verify or repudiate my understanding.
    package forums;
    import java.util.Random;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.ConcurrentHashMap;
    class GnatsThreadsafeCache
      private static final Random random = new Random();
      // pending locks := entityId --> lock
      private final ConcurrentMap<Integer, Object> pendingLocks = new ConcurrentHashMap<Integer, Object>();
      // cache := entityId --> entity
      //          1        --> "1"
      private final Map<Integer, Object> cache = new HashMap<Integer, Object>();
      public Object loadEntity(int entityId) {
        Object lock = new Object(); // shouldn't be final, see below
        // putIfAbsent: If the specified key is not already associated with a value,
        //  associate it with the given value. Returns the previous value associated
        //  with the specified key, or null if there was no mapping for the key.
        Object previousLock = pendingLocks.putIfAbsent(entityId, lock);
        if(previousLock != null) {
          // without using previousLock lock, there would be a chance
          //  for concurrent threads to perform redundant invocation
          //  of retrieveEntityFromSomewhereSlowly for same entityId
          lock = previousLock;
        Object entity;
        synchronized (lock) {
          entity = getEntityFromCacheQuickly(entityId);
          if (entity == null) {
            // cache miss - retrieve entity slowly:
            entity = retrieveEntityFromSomewhereSlowly(entityId);
            addEntityToCache(entityId, entity);
        pendingLocks.remove(entityId);
        return entity;
      private Object getEntityFromCacheQuickly(int entityId) {
        DEBUG("> getEntityFromCacheQuickly("+entityId+")");
        Object entity = cache.get(entityId);
        DEBUG("< getEntityFromCacheQuickly returns "+entity);
        return entity;
      private Object retrieveEntityFromSomewhereSlowly(int entityId) {
        DEBUG("> retrieveEntityFromSomewhereSlowly("+entityId+")");
        try{Thread.sleep(random.nextInt(1000));}catch(InterruptedException e){System.err.println(e);}
        Object entity = Integer.toString(entityId);
        DEBUG("< retrieveEntityFromSomewhereSlowly returns "+entity);
        return entity;
      private void addEntityToCache(int entityId, Object entity) {
        DEBUG("| addEntityToCache("+entityId+", "+entity+")");
        cache.put(entityId, entity);
      public static void main(String[] args)
        final GnatsThreadsafeCache cache = new GnatsThreadsafeCache();
        for (int i=0; i<10; i++) {
          new Thread(
            new Runnable() {
              @Override
              public void run() {
                int i = random.nextInt(4);
                Object entity = cache.loadEntity(i);
                DEBUG("~ "+i+"-->"+entity);
          , "Thread"+i).start();
      private static void DEBUG(String message) {
        System.err.println(Thread.currentThread().getName()+": "+message);
    }How it works:
    1. create a new lock object.
    2. check if entityId exists in the previousLock list... that's a ConcurrentMap so the putIfAbsent operation is atomic (i.e. syncronised on the previousLock object).
        ~  This operation is "garanteed fast"; ergo it involves no heavy "business object" creation/retrieval.
    3. Now, if the entityId already exists in the previousLock list we syncronize on it, allowing one-thread-at-a-time to traverse "the crytical block" where we check if the-entity associated with the-given-entityId is allready cached, and retrieve it, otherwise create a new one (which will take an arbitrary "long time").
    So what? Well I think it means that we've reduced contention to the individual entity level, as apposed to the "collection level"; as you would get if you just used a "standard" ConcurrentMap as the cache... which means that we've (probably) increased the throughput because each thread is blocked only upon those other threads which definately would stuff-them-up (waiting for the heavy "business object" creation routine to complete); as apposed to those that just might stuff them up (but won't because they're actually retrieving different entities).
    In short: It's a way of blocking on distinct keys?
    Is that correct?
    Thanx in advance for your thoughts.
    Cheers. Keith.
    Edited by: corlettk on 1/08/2009 11:05 ~~ Removed extranious cache.get from retrieveEntityFromSomewhereSlowly.

  • How do I get the client IP Address from the HTTPServletRequest object

    Hi ppl,
    How do I get the IP address of the client machine from the HTTPServletRequest object?
    Thnx in advance,
    Manoj

    Take a look at: http://java.sun.com/products/servlet/2.2/javadoc/index.html and check for the ServletRequest Interface.
    Be aware also if your web server is using proxy, proxyReverse and so because you could end getting the servers' IP and not client one.

  • HttpServletRequest Object Question?

    I need to manipulate the Header (specifically the Authorization) of an Http request made to a servlet. I would assume that the header is encapsulated in the HttpServletRequest object sent to the server, but I don't seem to have any way of accessing it.
    Any suggestions, advice?
    Thanks

    The header is included in the HttpServletRequest instance, but you might be misunderstanding that interface. HttpServletRequest instances are only meant to wrap a client request to some server- not the server's response. Thus, you can retrieve values from the request, but you can not set them (not through HttpServletRequest), because the instance only wraps a client's request. To set a header value, use HttpServletResponse:
    response.setHeader("Refresh", "15");
    ... you can get a Header value from the request by,
    request.getHeader("Refresh");

  • Question on HttpServletRequest object

    If I have a request object (say r), am I able to remove a parameter from that object and replace it in a servet?
    I am trying to take a double value from a form (not a problem) and pass it into a servlet. What I want to do is in the servlet, run some update code on the value, put it back into the request object, and then do the doPost method on it. Is that possible?
    Is it just as simple as r.removeAttribute(name) and a r.setAttribute(name,obj)? Or is it a little more complex than that?
    - Josh

    Parameters and Attributes are completely different things.
    Request parameters come from the HTTP Request. They can only be strings. Request Parameters are not normally editable.
    Request attributes are java objects. Its basically a useful space to store your java beans in.
    What I want to do is in the servlet, run some update code on the value, put it back into the request object, and then do the doPost method on it. Is that possible?What do you expect to trigger this "update" code? Isn't the doPost method the first entry point into the servlet? If you want to run something BEFORE the doPost of the servlet you might look at using a servlet filter
    Take a look at [This post|http://forums.sun.com/thread.jspa?threadID=682565] which discusses "editing" request parameters.
    Hope this helps,
    evnafets

  • Synchronize Session Objects

    Hi all,
    i have big problems using objects in session.
    Perhaps i only have a wrong view of this technology.
    1. Session objects could be used by serveral request.
    2. Requests of one user could run simultaneously (user click double on a link or opens two browser windows)
    => Every Read/Change on session object must be synchronized
    => And this must be done global for the app (could be that the access to a session object is done in different business logic methods)
    If this is ok, using helpful tags of additional technologies like JSTL (sessionScope.ObjectName) are absolutly wrong.
    Did i make an important mistake in my view.
    cu
    Johnny

    Session objects are usually implemented using cookies, which is also the same method your browser uses when it asks you if you want to save username/password information for a given site.
    But, as far as keeping information, why do you need to store the password in the session? Shouldn't the username (and possibly some permissions) be all the user data you need?

  • After downloading a book to the Iphone it did not show up on the IPad, although both are enabled.  I can locate both devises using the same Apple ID.  Is WiFi necessary to synchronize books through the iCloud?

    If both the iphone and ipad are locatable with the same apple id, should I expect the books purchased on one will appear in the book shelf of the other?

    Welcome to the Apple community.
    In order to make a purchase from one device download to another, you need to enable automatic downloads on that device at settings > store.

  • Getting Server IP Address using HttpServletRequest object

    Hi
    I am writing code using servlets ,
    My system is on LAN let say its IP is suppose 192.0.0.1 and i have another computer name "A" on Lan with private ip 192.0.0.2 and also its has public IP 12.0.0.10 suppose.
    When i recive request from i try to get its public IP using methods
    request .getRemoteAddress(), but problem is i am getting its private IP i want to get its public Ip how i can get it

    Are you running dual network interfaces in each machine?
    If so, and the packet you're attempting to analyze for public IP address is being received over the local network, I don't think there's a way to accomplish this outside building a lookup table or some such manually.
    Or is there some sort of "fun" routing system in place here?
    ...or have I completely misunderstood the question? :)
    -Kyle

  • Object/variable synchronization

    i need to synchronize a primitive type (or object), am i doing it correctly?
    private static boolean threadStarted = false;
    public void init(){
        sunchronized (threadStarted){
            if (!threadStarted){
                schedulerThread = new Scheduler();
                schedulerThread.start();
                threadStarted = true;
    }this is basically a servlet that does some database maintainance (I'm forced to make it a Servlet - so we can do different DB maintainance task from anywhere, by using the HTTP GET).
    what i wanted to happen is that on init(), the servlet will create an instance of the Scheduler(which extends Thread to create and starts severals TimeTask objects using a Timer). i wanted to make sure only the scheduler thread is ever created get created once and started once. is the above code guareentee to start only one instance of the scheduler.
    my previous code does not have synchronization, and i noticed that the scheduler is created twice 9therby - doing the same DB maintainance twice - which is extremely costly)
    I thought of making the Scheduler a Singleton, and return null if the instance has been created...like the code below
    public class Scheduler extends Thread{
        private static Scheduler scheduler = null;
        private Scheduler(){
            // .. initialize some local variables in here
        public synchronized static Scheduler getInstance(){
            if (scheduler == null)
                return new Scheduler();
            return null; 
        public void run(){
            // do some thread stuff here
    public void init(){
        Scheduler temp = Scheduler.getInstance();
        if (temp != null){
            schedulerThread = temp;
            schedulerThread.start();
    } any comment or better design? (yes, i have to use a servlet)

    First, synchronized has a 'y' in it, not a 'u'. :^)yeah, i have a bad habit of typo. for me, most compile error (90%) aare typo
    i really need to take a typing class or two.
    Second, your methodology of checking null before creating the object involves
    a race condition. Two requests, theoretically, could come in at the same time,
    and you might get unexpected results. actually..the method is synchronized, so there wont (shouldn't) be any race condition. the first time the method is invoke..it will lock the method from all other..until the method is complete. I think this is pretty much a standard way of doing a Singleton (cept return null should be returning the scheduler object.)
    I aslo knows about double locks and its flaw..that's why the method is synchronized instead of using lazy creation method.
    You can only synchronize an object, so you would have to wrap boolean in an
    instance of java.lang.Boolean. cool, this i didn't know about. guess i can make the primitive a Boolean instead of a boolean.
    Be VERY wary of spinning off your own threads in a J2EE container (e.g.,
    Servlet). The J2EE specification specifically requests you avoid doing this. The
    primary reason is that the container should be responsible for multi-threading
    and thread management. That having been said, you CAN spin off your own
    threads, just be very careful.yes, i heard about this so many time..but there's really no choice but to use thread in my application. that's why i come here to ask..hoping someone works with this type of problem before..and know a better design.

  • How to create a new object of HttpServletRequest class manually?

    Dear all,
    I don't know how silly my question is, however I have no way except asking.
    I know that when I send a request from the client to the server, server authomatically creates an object of
    HttpServletRequest and assigns all the request information to that object, so that you can extract these information by the available methods in the HttpServletRequest class like getHeader, getMethod and so on. What I need to do in my project is doing all above process manually. My question is how I can do it?
    In other words, I have the header and body part of a http request and I want to create a HttpServletRequest
    object and assign the header and body data to the object so that I'll be able to extract those data by using the getHeader, getMethod and other methods available in the HttpServletRequest class.
    Please Help me, I really need your help?
    Your help is appreciated.
    Thanks.

    Hi shadgar ,
    as rightly mentioned by Sudha and GrayMan, you can provide the implementation for the HttpServletRequest interface in your own way for the requirement, but it leads to a new Servlet Container development as you need to handle many things than the HttpServletRequest.
    I think the current interface and the Servlet Container will be able to handle if your request is over HTTP protocol and it don't deviate from the prtocol's request/response model.
    Check out the javax.servlet.http.HttpServletRequestWrapper class, which is the implementation of the javax.servlet.http.HttpServletRequest and javax.servlet.ServletRequest interfaces.
    Hope it will give some idea about the actual problem and rethink about the solution proposed.
    Thanks,
    Sanath Kumar

  • How to synchronize objects

    Hi All,
    I have a report which shows count of various objects in a report.
    These objects are coming from different data providers i.e. Universes and Stored Procedure.
    Now, the problem is, report is showing proper count for the objects which are coming from Universes, but its showing wrong count for the objects that are coming from Stored Procedures.
    So, anyone has any idea how to synchronize these objects coming from different data providers i.e. Universes and Stored Procedure ?
    Thanks in advance.

    Hi Harshad,
    Could you please review the  following simulation if the issue is according to the below mentioned information then test the solution.
    Requirements:
    1. Report X based on two blocks A and B issued from two data providers A and B.
    2. Data provider A based on an stored procedure A providing a dimension A (DimensionA displaying figures with a NUMERIC TYPE).
    Block A
    Column A
    1
    2
    10
    5
    3. Data provider B based on a universe B and a dimension B with a CHARACTER TYPE.
    Block B
    Column B
    8
    9
    11
    25
    To synchronize the dimensions A and B the idea is to turn the NUMERIC TYPE of the dimension A into a CHARACTER TYPE as the B one.
    As the type of the dimension A cannot be changed within a report, the idea is to export the stored procedure storing the table A and the column A to an Access database as a table A.
    Inside Access the column A having a NUMERIC TYPE can be turned into a CHARACTER TYPE.
    The following step is to insert into a universe A the table A and its column A to create a dimension A.
    Having a CHARACTER TYPE the dimension A can be linked to the data provider B containing the dimension B
    STEPS
    1. Import the table A from stored procedure within an Access database A as table A.
    2.Turn the type of the stored procedure numeric field into Access as a CHARACTER TYPE.
    3. Create a universe A based on the access table A.
    4. Open the report X.
    5. Insert a table on the universe A, and select the table A.
    6. Open the micro cube.
    7. Start the synchronization between the objects A and B.
    As the objects A and B have the same CHARACTER TYPE. These objects can be successfully synchronized.
    I hope this will help you.
    Regards,
    Sarbhjeet Kaur

Maybe you are looking for