Waiting in servlet

My Servlet (actually a JSP) should do the following:
1. process user input
2. make a http-request to a third party server
3. await the response
4. read and process the response
5. send a replay back to the user
The problem is step 3, it can take many second (up to 150), so if I get 10 requests per second, my threads can accumulate up to 150*10. And 1500 threads can be a serious problem, right?
Actually, I expect the waiting time to be usually shorter, but the number of requests can be higher.
Is it possible to do the waiting somehow without a sleeping Thread? For steps 2, 3 and 4 I could use java.nio, but because of 1 and 5 I need a sleeping Thread anyway....

There is a timeout function in javascripts which takes two parameters one of them is the time to wait in mills and the other is a string containing a valid java script statement to be executed once the time out occures.
I have used that in several projects and never had a problem.
But remember when you are implementing polling also think about the load that you are creating becouse of repeated polling.
Also try to get the server side part up and running first because that is the place where you might get various implementation issues most probably.
Here is a link to the details of the timeout function
http://www.w3schools.com/js/js_timing.asp
EDIT: You can also try to use AJAX for polling becouse it will look better on the browser.

Similar Messages

  • Jsp waiting for servlet response how to make

    Hi All,
    i have some doubts about making servlet response for jsp request
    Am watched some online reservation sites it search some hotel names untill the hotel names display (between that time)
    the image processing shows how can i make like that via jsp and servlet plz expalin with example code plz.
    how to make jsp wait to servlet response like that plz reply
    Thanks

    It's a client side thing. Learn Javascript (and CSS) and if necessary also learn Ajax afterwards. There are nice tutorials at w3schools.com. This issue is not really related to JSP/Servlets.
    Displaying the progress image isn't that hard. Just show some <div> element with an image during the onclick.

  • Wait() and notifyall() problem in servlet.

    Can anyone help me with this.....
    I am creating an application which has one gateway inside which
    handles for logger, dbmodule etc are made and passed to biz logic.
    This biz logic using logger obj made in gateway, does the logging.
    Now i hv to do serial implementation of logging i.e I have
    a static member which is of type Vector, which will hold
    a list of messages and associated parameters. The write() method will
    create a formatted message with all values inserted, all prefixes and
    suffixes added, etc. Then it will append the message to the Vector of
    messages. And there will be a separate thread, which will be started
    the
    first time the first Logger instance is created. This thread will keep
    picking up messages from this Vector in FIFO order and writing them
    out.Mind you, I don't mean i need to use a single shared Logger
    instance.
    Separate Logger instances must be used to hold separate values for
    sessionID, username, etc. Only the internal logging I/O stream handle
    should be shared.
    For this what i hv created logger class as follows:
    logger {
    SyslogAppender SA;
    logger() {
    new SA;
    ThreadGroup TG = new ThreadGroup("string");
    Logging target = new Logging();
    Thread DT = new Thread(TG, target, "daemon");
    DT.setDaemon(true);
    DT.start();
    class write {
    write() {
    //initialisation;
    void writetovector() {
    addtovector
    notifyall;
    class logging implements runnable {
    public void run() {
    while(vector is not empty){
    log
    synchronised(this){
    wait();
    Now in the servlet, in init(), logger is called with this constructor
    and therefore there is only one instance of syslog appender to log in
    syslog.
    In service i just call the function writetovector through a method in
    logger.
    However when i run the implemented version of this, logging does not
    take place.
    I feel my implementation of wait and notifyall is not correct. Or is
    there any other problem?
    thanx in advance

    There are many problems with your code. It looks like you retyped it, and it now contains many syntax errors. Two problems I can see, though, are that you do not call notifyAll from synchronized code, and your call to wait is not in a loop.

  • Wait and notify in servlets?

    i am having a servlet , which is implementing wait and notify of java.lang.Object.
    when serving it for single request , its waiting and working fine...
    but for multiple requests its not serving properly. works one by one means the second request is waiting for finishing the first request just like SingleThreadModel (after finishing the first request only second request entering inside servlet)
    please help me to solve this?
    or is there any other way to call wait method without synchronized block??

    Shynihan wrote:
    or is there any other way to call wait method without synchronized block??No, and that's partly because if wait or notify is the only thing in the synchronized block then you probably aren't using them right. The problem is blocking the server thread. Servlet engines use a thread pool to execute transactions, when a new transaction comes in a thread is taken from the pool to run it, and there's usually a limited number of threads in the pool. If there's no threads left then the transaction will wait for another to finish.
    If your servlets freeze up, then that's a thread gone from the pool.
    And remeber the unlocking transaction may never arive. The client could go down at any time, leaving the server thread permanently hung.
    You need to move this waiting to the client side. If the transaction cannot proceed then return a "come back later" response immediately. The client can then retry after a decent interval.

  • How to Wait in a servlet?

    I want to use this command:
    wait(500);
    I have a simple HTTP servlet class (public class SleeperServlet extends HttpServlet) but I get this error:
    java.lang.IllegalMonitorStateException: current thread not owner
    Anyone know how to do what I want to do?
    thanks for helping

    The reason you are getting the IllegalMonitorStateException is because you are using the wait method without being in a synchornized code block. Either you should do as is suggested and use Thread.sleep() or you should place a synchronized code block around the wait method. I would not suggest this as it may cause problems in the server with multi-threading.

  • Call unix script within Servlet - need to wait for completetion

    Hi,
    I have a servlet which grabs some information from my web form and then calls a unix script.
    This already works fine and does what i need it to do. I now need to add some functionality where i can get the servlet to wait for the unix script to complete before carrying on and then redirecting back to the user.
    the code i have for the current servlet is:
             * EXECUTE THE UNIX COMMAND.
            Runtime   oRuntime  =     Runtime.getRuntime();
            Process   oProcess   =     null;
            String[]      cmd          =     {"/bin/sh", "-c", sPath}; // UNIX
             * ERROR CODES 3 = File not found
            try
              oProcess = oRuntime.exec(cmd);
            catch(Throwable t)
              t.printStackTrace();
            }I am assuming i need some sort of wait method to handle this. Any help would be greatly appreciated.
    Thanks
    Graham

    ok.. you code is fine.. you can run any shell script or program using the exec() method. if you need to wait till the process finishes then you need to call the method waitFor() in class Process.. the method blocks the parent thread (servlet) till the sub process (your exec'd script or program) terminates.
    hope that solves your problem.. :-)
    Pls tell me one more thing.. are you using netBeans or Eclipse for executing the programs or you use standalone tomcat to deploy the application. I have problem in execing programs when i deploy in tomcat 5.5 and the same application works fine in netBeans 5.0. if you know pls help me too..
    Thanks,
    -- abdel Olakara.

  • Servlet waiting for threads to end

    Hi !
    To make our web app more efficient, we wanted to delegate some work to threads. But it seems that the servlet engine (or something else) is waiting for all spawned threads to end before sending the response back to the browser. So, if a servlet finishes execution but the threads it spawned are still working, I do not get the next page in the browser. I only do when all threads are done. So my question is : is this a normal behavior of the servlet engine ? If so, why ? If not, what could I have done wrong, what should I look out for when using threads inside servlets ?
    Thanks,
    Martin

    Yup I agree with the other guys.
    I am building a servlet that has 2 threads running continuously (looping), and they do not bother the requests/responses at all. But in your case if I understand correctly, you spawn threads from the request. You must have some kind of interaction between them.
    Are you sure you are spawning the code in a separate thread??. I use something like this:
    class Mythread extends Thread
    public void run()
    // code here
    THread threadobject = new Mythread();
    threadobject.start(); //( DO NOT CALL THE run() method, but the start() method.)
    Are your threads sleeping (to not hog up all CPU power???). Are your threads higher priority then the normal?.
    See ya,
    Andre

  • Sending a request to a servlet without waiting for a response

    Hi,
    I have a client application that needs to send information to a servlet for processing. I would like to be able to send the information in question without having to wait for a response from the servlet. The reason for this is that I want to speed up the "sending" process. I know that http communication is based on TCP which is a connection-oriented network protocol, but I thought maybe there was a work-around to this.
    Thanks in advance for your help,
    Chris

    There r two ways to do this. First, if you can modify the application simply don't wait for the response do whatever you want and ignore the response. If you need the response in order to continue you will have to wait, but you can do this in a separate thread, while the main thread can do other things.
    Second, if you can't modify the application but you can modify the servlet, make the servlet respond as quick as possible, doing the work after having answered. Once again if the application needs the results of the process there is no way, you'll have to wait.

  • Make a servlet wait for  a resource and respond based on the resource

    Hi,
    In my web application, my javascript code sends a request to a servlet for an image .
    In the server side, my servlet checks whether the image exists in a particular path, if it exists it sends the image
    as a response, else will wait in an infinite loop for the image. Once the image is available, it will exit the loop and will proceed further.
    Is my logic to put an infinite loop right .
    kindly provide me an alternative method if my logic is wrong.

    Your request may simply time out.
    Alternatively you can consider kicking off the image processing in the backend on first request and send a response back to the browser that would cause the browser to resend the request every 'x' seconds. You can achieve this by setting a metarefresh tag in your header or anyschronous javascript.
    ram.

  • Servlets, Threads, sleep and wait

    Hi,
    I am new to servlet programming and have a problem.
    I want to create a servlet that is also Runnable. It should hold the HTTP request open, and then wait() or sleep(), waking up regularly to send data to the client.
    My code seems to work OK, and in the server logs I can see the debug messages where my servlet is sleeping and waking up. However, it doesn't keep the connection open. Instead, any clients that try to connect instantly receive an empty response.
    Can anyone explain why this is? I am a bit lost. Is the server (Tomcat) cutting my request off when I start to sleep or what?
    dave

    OK. Now seems like I have it working with sleep().
    I was doing something pretty dumb and assuming that a new HttpServlet instance was created for every request - doing things like this.request = request; - obviously this didn't work too wlell ;-)
    Now just using Thread.sleep() it works much better
    One more question - how can I get a separate servlet to call notify() on this servlet so that it wakes up and delivers its message? (I know I need to call wait() not sleep())
    Thanks
    dave

  • Servlet, wait and an asynchronous call.

    Hi Guys,
    Need some guidance. Here is what I am trying to design.
    I have a swt client that connects to a servlet via apache's httpclient and sends a request. Upon receiving the request, the servlet publishes it to a different component asynchronously. The component after a bit of processing (usually 1-2 seconds) will start to send responses intermittently for a given number of seconds. The servlet will receive and forward them to the client.
    The challenge for me it to make the servlet wait till the component has started to publish the responses and written multiple responses back to the client.
    Here is what i have come up with: The servlet gets the request from the client, calls a class that has a thread to publish it to the component. The thread will wait till the component sends back a response. Once the response is received (by a different thread), the waiting thread will be notified and the control will go back to the servlet. The servlet will flush the response and wait for the subsequent responses.
    Does it sound feasible or have I neglected some key issues? Any ideas, links, code snippets would be very helpful.
    Cheers,
    Vic
    Message was edited by:
    vics_31
    Message was edited by:
    vics_31

    make your worker thread put the responces in a blocking queue and make the servlet read from the queue. So when the queue is empty it has to wait.
    But normally we do not create threads in servlets its a bit unusuall design.

  • Waiting for a process kicked off by servlet

    I am kicking off a script on a Unix machine from my servlet on os390 using,
    Process p = rt.exec("full_path/script");
    How do I know when the process is complete so that I can show the xml page that the process is creating?
    Justin Mennen
    [email protected]

    there is a method waitFor() in Process meant for that purpose

  • Parameters from midlet to servlet

    Hi all,
    i have been trying to pass values from MIDlet (setRequestProperty(); ) and to servlet (request.getParameter();).
    but when i tried to print out the value, it just contained NULL value.
    I had a look at the java forum website, there were plenty of same problems and no one got right.
    I'll really appreciate it if anyone fixes this for me.
    ---------------------MIDLET-----------------------------------------------------------------------------
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    import java.util.*;
    import org.kxml.*;
    import org.kxml.parser.*;
    public class MbankMIDlet  extends MIDlet implements CommandListener {
      private Display display;
      private Form loginForm = new Form("Login");
      private Form mainForm = new Form("MobileBank");
      private String loguserID;
      private String logpass;
      private String mSession;
      private StringItem stringItem = new StringItem(null,"");
      private TextField userIDTextField = new TextField("User ID", "", 8, TextField.NUMERIC);
      private TextField passwordTextField = new TextField("Password", "", 12, TextField.PASSWORD);
      static final Command loginCommand = new Command("Login", Command.OK, 1);
      static final Command exitCommand = new Command("Exit", Command.STOP, 1);
      static final Command backCommand = new Command("Back",Command.BACK, 1);
      public MbankMIDlet() {
        mainForm.append(stringItem);
        mainForm.addCommand(exitCommand);
        mainForm.addCommand(backCommand);
        mainForm.setCommandListener(this);
      public void startApp() throws MIDletStateChangeException {
        display = Display.getDisplay(this);
        loginForm.append(userIDTextField);
        loginForm.append(passwordTextField);
        loginForm.addCommand(loginCommand);
        loginForm.addCommand(exitCommand);
        loginForm.addCommand(backCommand);
        loginForm.setCommandListener(this);
        display.setCurrent(loginForm);
      public void destroyApp(boolean unconditional) {
        notifyDestroyed();
      public void mainMenu() {
        display.setCurrent(loginForm);
      public void pauseApp() {
        display = null;
        loginForm = null;
        mainForm = null;
        stringItem = null;
        userIDTextField = null;
        passwordTextField = null;
      public void commandAction(Command c, Displayable d) {
        String label = c.getLabel();
        if (label.equals("Exit")) {
          destroyApp(true);
           mSession = null;
        } else if (label.equals("Login")) {
          login();
        } else if (label.equals("Back")){
          mainMenu();
      private void login() {
        loguserID = userIDTextField.getString();
        logpass = passwordTextField.getString();
        Form waitForm = new Form("Waiting...");
        display.setCurrent(waitForm);
        Thread t = new Thread() {
          public void run() {
            connect();
        t.start();
      private void connect() {
        HttpConnection hc = null;
        InputStream in = null;
        OutputStream os = null;
        String url = getAppProperty("MbankMIDlet.URL");
        try {
          hc = (HttpConnection)Connector.open(url);
          hc.setRequestMethod(HttpConnection.GET);
          hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
          hc.setRequestProperty("Content-Language", "en-US" );
          hc.setRequestProperty("Accept", "text/plain");
          hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
          hc.setRequestProperty("Connection","close");
          hc.setRequestProperty("loguserID", loguserID);
          hc.setRequestProperty("logpass", logpass);
          os = hc.openOutputStream();
          os.close();
    //      os.flush();  //tried close() and flush() but none of them worked.
          if (mSession != null) {
              hc.setRequestProperty("Cookie", mSession);
          // Read the session ID from a cookie in the response headers.
          String cookie = hc.getHeaderField("Set-cookie");
          if (cookie != null) {
              int semicolon = cookie.indexOf(';');
              mSession = cookie.substring(0, semicolon);
          in = hc.openInputStream();
          int rc = hc.getResponseCode();
          if( rc == HttpConnection.HTTP_OK ) { //HTTP_OK equals 200
            System.out.println("HttpConnection OK");
            StringBuffer xmlBuffer = new StringBuffer();
            String xmlString = null;
            int ch;
            while ( ( ch = in.read() ) != -1 )
              xmlBuffer.append( ( char )ch );
            xmlString = xmlBuffer.toString();
            stringItem.setText(xmlString);
          else if (rc == HttpConnection.HTTP_UNAUTHORIZED){//HTTP_UNAUTHORIZED equals 401
            System.out.println("HttpConnection Unauthorized");
            int contentLength = (int)hc.getLength();
            byte[] raw = new byte[contentLength];
            int length = in.read(raw);
            String s = new String(raw,0,length);
            stringItem.setText(s);
          in.close();
          hc.close();
        catch (IOException ioe) {
          stringItem.setText(ioe.toString());
        finally {
          display.setCurrent(mainForm);
    }---------------SERVLET----------------------------------------------------------------------------
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              HttpSession session = request.getSession();
              response.setContentType("text/plain");
              PrintWriter out = response.getWriter();
              String userID, password, userRole = null;
              try {
                                  userID = (String)request.getParameter("loguserID");
                  password = (String)request.getParameter("logpass");
                  System.out.println(userID); // "Null printed"              System.out.println(password);  // "Null printed"
              catch (Exception e) {
                   //If anything goes wrong, print the Exception message
                  e.printStackTrace(out);
    }Thanks.

    getParameter() can't parse the input stream well if there is any issues in the sent content. this is true, with varying mobile phone http impl.
    You would find the content at servlet, by using request.getInputStream() and reading the entire content.
    Here is the sample code:
    public static String readMobileData(final HttpServletRequest aRequest) throws Exception
         String lData = null;
         Enumeration params = aRequest.getParameterNames();
         while (params.hasMoreElements())
         //from real Nokia 6600 Mobile the request is sent as param, though
         //it is post
         String lName = params.nextElement().toString();
         lData = aRequest.getParameter(lName);
         System.out.println("\nParameter:" + lName + "=" + lData);
         if (lData == null)
         //in emulator the data is coming as inputstream
         ServletInputStream in = aRequest.getInputStream();
         DataInputStream dIn = new DataInputStream(in);
         lData = dIn.readUTF();
         lData = lData.substring(lData.indexOf("=") + 1);
         System.out.println("Stream Request:\n" + lData);
         return lData;
    Regards,
    Raja Nagendra Kumar,
    C.T.O,
    When Teja is Tasked, the Job Gets Done
    www.tejasoft.com

  • Forms Client Java Applet waiting several minutes

    Hello,
    We use Forms 10.1.2.0 and html/javascript/plsql applications.
    All forms applications are working but
    we have the problem that from time to time the client java applet must wait minutes until there is an answer from the forms-servlet (especially when there is high activity in the system).
    More than one user is working in the form with high activity - the applet sends a request
    over the network - after 4 minutes the result is shown and you can go on working
    without problems.
    So a lot of users think the application has crashed and terminate before.
    The applet shows no error messages.
    There is no sign that there is a lost connection between applet and servlet.
    It is not reproducible. That means you can work 2 hours and everything is ok
    or you work 5 minutes and you have to wait.
    network problems?
    firewall problems?
    do requests of the forms servlet to the database have minor priority on the application server
    than html/plsql requests?
    any ideas?

    when the problem occurs (user has to wait 3-4 minutes) we found in the log
    3 heartbeats from the forms client within 2 seconds ?
    after 3-4 minutes the forms client is ok (user can go on working)
    and the pings are every 2 minutes (like it is expected).
    The application.log file may contain duplicate posts requests with
    identical pragma header numbers, indicating that the client
    is resending
    requests due to network packet losses. Under normal circumstances,
    only the last Post request, terminating a Forms session,
    should contain
    a duplicate pragma header number.
    ...a network problem ?
    anyone else who had the same problem ?

  • Global data in a servlet using iPlanet Web Server

    Our configuration is an Applet->Servlet->JNI->C/C++ code.
    We have C code that does a number of lengthy mathematical calculations. This C code not only uses its own global variables but, it is also comprised of numerous subroutines that all call each other, reading and writing global C variables as they go. These globals are all isolated to the C code shareable object (.so) library that is included using the LoadLibrary call when the servlet is initialized.
    The problem is that in a multi-user environment (3-5 simultaneous users) we need to have each user have their own "copy" of the servlet (and the C code) so that users will not be accessing each other's global data. We can NOT have only one copy of the C code and define it as synchronized because the calculations that are performed can take a very long time and we can not hold off user requests while the firs user finishes.
    Our hope is that there is a way to configure the iPlanet Web server such that each new user that starts up a copy of the Applet/Servlet combination will get their own "space" so that they can work independently of any other user. We have at most 20 users of this system and only 3-5 simultaneous users so we should not have a problem with memory or CPU speed.
    If anyone has a solution, I would greatly appreciate it!

    The C library is shareable. But you don't want it to be shared. That's your question summarized, isn't it?
    You probably can't prevent it from being shared, so to prevent multiple use of it you would have to queue up the requests to be done one at a time. WynEaston's suggestion of having the servlet implement SingleThreadModel would help, but I believe the servlet spec allows servers to run multiple copies of a servlet that does that (as opposed to running a single copy in multiple threads).
    Your other alternative is to rewrite the math in Java, or at least in some object-oriented language where you don't need global variables (which are the source of your problem). All right, I can already hear you saying "But that wouldn't be as fast!" Maybe not, but that isn't everything. Now you have a problem in queueing theory: do you want a single server that's fast, but jobs have to wait for it, or do you want multiple servers that aren't as fast, but jobs don't have to wait? That's a question you would have to evaluate based on the usage of your site, and it isn't an easy one.

Maybe you are looking for

  • Photos

    We have multiple users on our computer. One of the users has all of the photos from our old computer under his account. Is there anyway to access the photos from his account while being on mine? 20" iMac Intel Core Duo   Mac OS X (10.4.7)   2 GB RAM

  • Material Ageing Report Through ABAP( MC46 Tcode Wise)

    Hi, I want to develop report for Material Ageing Report which is similar to the Tcode MC46 but the problem is functional consultant told me about this tcode only and there is no such information regarding the specified tables which are to be used. I

  • Display PDF on opening new browser

    Hi Experts, Requriement: We need to open a new browser for dispalying PDF format converted from custome smartform. Currently I am able to view the PDF format on a new screen with the following code, but user want to see the same PDF format on new bro

  • Restore primary database using physical standby

    hi, i am taking rman backup on production database,we have physical standby.coming month i have to take backup from standby instead of prod db.pls advise me, is it possible to restore and recover production database using standby database backup.if p

  • Some vids won't import to iMovie, help?

    When I try to import something from iTunes and the window pops up, some of the movies are greyed out (like the stuff that aren't even movies). I've downloaded all of my movies off the internet, and they normally work aftered I've converted them to iT