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

Similar Messages

  • Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced.

    Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced while changing OS time.
    I found a BUG in java bug list. The bug id is 6311057 with fixed status. But I find it still existing.
    Under CentOS6 x64 platform, on JDK1.6.0_33, the bug still exists.
    But under CentOS5 x64 platform, on same JDK, the problem does not exist.
    Could anyone give me help? Thanks.
    The bug's link is http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6311057
    Edited by: user10222290 on 2012-6-13 下午9:22

    user10222290 wrote:
    One server could want to synchronize it's OS time with another server when they connected each other for some business reasons. I have 3 computers running pretty much continuously with time synchronised from one of the internet time servers. They never seem to be more than about 1/10 th second apart and any time corrections are very very small.
    Some threads have started to run before changing OS time, so these thread's sleep process will be influenced sometime seriously.I understand that but I would only expect this to be a problem when there is a significant change to the OS time. If each server is synchronized to a time server then the time corrections will be very very small.
    If OS time was turned back some days, these thread could not wake up untill some days passed.Agreed but why would the "OS time be turned back some days" ?
    This whole problem seems to me to arise because the servers are not time synchronized. Now I understand that there may be concerns about the security of external time servers but it is easy enough to make one of the local servers a master and act as a time server to the others.
    I have a small server that typically services some 30 or so external clients. I don't have any control over the clients and do not know anything about the setting of their system clocks. The clients send a time signal as part of a heartbeat and from this the server keeps track of the local time on each client and compensates for any difference when writing logs. I have seen this difference as big as 4 months but the compensation corrects it to within about a second. No adjustment of clocks is required for this.
    I still don't see this 'bug' as a serious bug. I just see a design problem to be solved without changing the OS time on any computer. I know this can be done since I do it. The only problem I see is if you want an accuracy of better than about 20 mS but that does not seem to be required for your system.
    Note - if Oracle accept your new bug report it could take years to fix even if lots of people vote for it to be fixed.

  • Query on Timer ,Sleep and Wait .

    Hi all ,
    Please bear with me if my query has been discussed here before .
    I am using JDK 1.3 ...and I need to implement a javax.TV.util.Timer and also use Thread.Sleep(long) and Obj.wait(long) in my stack .
    I need to know what will be the effect on each of these if i change the System time after scheduling each one of the above .Both ,when the system time is set to a previous time and when the system time is set to a time in future which is greater than the "long" duration input given. ?
    At this point of time i cant verify this on my own but it would speed en up when i do get my test setup up n running..
    If changing the system time does affect the functionality then it would be very helpful if the solution too is provided on how to mitigate the problem..
    Thanks in advance

    Do not crosspost all over the place.
    Post it once in the forum you think is most appropriate.
    - Roy

  • Difference between thread.sleep and BufferedReader.readline()

    Hi All,
    I have J2SE application which is infact a listener, to keep it working for 24/7 what you people suggest do i use
    while(true)
    Thread.sleep(10000);
    or
    BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
    System.out.print("Enter Quit to Exit.. ");
    String cmd = br.readLine().trim();
    if (cmd.equalsIgnoreCase("quit"))
    System.out.println("Quitting...");
    System.exit(0);
    Please also suggest which one is optimized solution.
    Regards,
    raza

    emmi@java wrote:
    HI,
    My application is J2SE based not web based.
    RegardsSorry, could have sworn I read J2EE.
    In any case, a thread is exactly what you want. And neither "sleep" nor "readline" but a simple wait().
    Edit: And, yes, the real question is, as already asked, what do you mean by "listener"?

  • Thread.sleep and Thread.yield

    hi,
    anyone knows the difference between these 2 methods ?
    so far as i can see, the only diff is that sleep takes in an argument (time in millis) whereas yield does not.
    also, both methods hold on to the locks and dont give them up.
    pls comment

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#sleep(long)
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#yield()
    pretty clear...

  • Multi-Thread application and common data

    I try to make a multi-Thread application. All the Threads will update some common data.
    How could I access the variable �VALUE� with the Thread in the following code:
    public class Demo {
    private static long VALUE;
    public Demo(long SvId) {
    VALUE = 0;
    public static class makeThread extends Thread {
    public void run() {
    VALUE++;
    public static long getVALUE() {
    return VALUE;
    The goal is to get the �VALUE� updated by the Thread with �getVALUE()�
    Thanks for your reply
    Benoit

    That code is so wrong in so many ways......
    I know you're just experimenting here, learning what can and can't be done with Threads, but bad habits start early, and get harder to kick as time goes on. I am going to give a little explanation here about what's wrong, and what's right.. If you're going to do anything serious though, please, read some books, and don't pick up bad habits.
    Alright, The "answer" code. You don't use Thread.sleep() to wait for Threads to finish. That's just silly, use the join() method. It blocks until the threads execution is done. So if you have a whole bunch of threads in an array, and you want to start them up, and then do something once they finish. Do this.
    for(int k=0; k<threads.length; k++) {
      threads[k].start();
    for(int k=0; k<threads.length; k++) {
      threads[k].join();
    System.out.println("All Threads Done");Now that's the simple problem. No tears there.
    On to the java memory model. Here where the eye water starts flowing. The program you have written is not guarenteed to do what you expect it to do, that is, increment VALUE some amount of time and then print it out. The program is not "Thread Safe".
    Problem 1) - Atomic Operations and Synchronization
    Incrementing a 'long' is not an atomic operation via the JVM spec, icrementing an int is, so if you change the type of VALUE to an int you don't have to worry about corruption here. If a long is required, or any method with more then one operation that must complete without another thread entering. Then you must learn how to use the synchronized keyword.
    Problem 2) - Visiblity
    To get at this problem you have to understand low level computing terms. The variable VALUE will NOT be written out to main memory every time you increment it. It will be stored in the CPUs cache. If you have more then one CPU, and different CPUs get those threads you are starting up, one CPU won't know what the other is doing. You get memory overwrites, and nothing you expect. If you solve problem 1 by using a synchronized block, you also solve problem 2, because updating a variable under a lock will cause full visiblity of the change. However, there is another keyword in java.. "volatile".. A field modified with this keyword will always have it's changes visible.
    This is a very short explaination, barely scratching the surface. I won't even go into performance issues here. If you want to know more. Here's the resources.
    Doug Lea's book
    http://java.sun.com/docs/books/cp/
    Doug Lea's Site
    http://g.cs.oswego.edu
    -Spinoza

  • Repaint() being delayed by Thread.sleep()

    Hello, I am programming a Memory-like card game, where the user picks cards and if they match they stay flipped over, but if they don't match the cards will be displayed for a second and then flipped back over. However, I am running into a problem when the cards do not match, the game will wait (using Thread.sleep()) and then flip the cards back over. The problem is that the second card picked, that is determined to not be a match, is not showing the face before the cards are returned to the hidden state. I think that it is being flipped twice in a row at the end of the sleep(), therefore never actually displaying the front of the card. I have tried putting repaint() everywhere, and there is one before the sleep(), but it still doesn't seem to work properly. Here is the code for my mouse clicked event. Thanks for any help!
      public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        Card temp = null;
        for (int i = 0; i < 52; i++) {
          temp = cards.getCard(i);
          if (temp.contains(x, y)) {
            if (temp.isFront() == true)
              return;
            temp.swapImg();
            this.repaint();
            if (flipped == null) {
              flipped = temp;
            } else {
              if (temp.getVal() == flipped.getVal()) {
                // we have a pair
              } else {
                // cards don't match.. start over
                try {
                  Thread.sleep(500);
                } catch (InterruptedException ie) {
                  System.out.println("Thread was interrupted!\r\n");
                temp.swapImg();
                flipped.swapImg();
              flipped = null;
            break;
      }

    Don't use Thread.sleep() inside a Listener. You are blocking the EDT which prevents the GUI from repainting itself.
    Use a Swing Timer to schedule the flipping of the cards.

  • Realtime equivalent to Java's Thread.sleep()?

    I have an application that I want to guarantee that when I call Java's Thread.sleep(n) the thread will sleep for precisely that amount of time, or close to it at least. What we recently encountered though was that if the "wall clock" time is changed in one thread while a sleep is occurring in another thread, this clock change will impact when the sleeping thread will wake up.
    In our case, we had a simple Thread.sleep(1000), and during that one second period another thread set the clock back two minutes. The sleeping thread ended up sleeping roughly two minutes and a second instead of just a second. Apparently this is a "feature" of Thread.sleep(), and I can see in some cases (e.g. a task scheduler based on wall clock times) where this is exactly the behavior you'd want. However, in our case, we want the sleep function to sleep by the amount we specify, regardless of changes to the wall clock time. Is there a way to do this in Java? We are using JDK 1.5.

    You can use methods which rely on the nanoTime() (based on the number of clock cycles since the processor last reset)
    Classes such as LockSupport.parkUntil(someObject, nanoTime) may give you the accuracy/consistency you want. In this case you always wait the full delay.(and not unpack it)

  • NCO 2.0 problem in commit and wait

    Hi there,
    I use NCO 2.0. It provides a SAPClient.CommitWork() method to implement BAPI_TRANSACTION_COMMIT. However, it doesn't support commitandwait function. Now, my problem is how do I know my BAPI execution has committed ? 
    here is my scenario:
    I execute BAPI_SALESORDER_CHANGE to create a sales order items. Then I use SAPClient.CommitWork() method to commit the work. Sequently, I execute a RFC function to write WBS for each order item. The error occured and showed that "the salesdocument was locked". I think it is because the commit action has not finished.
    If I add thread.Sleep() to wait 5 seconds, then I can successfully execute the RFC function to update WBS.
    So, how could I know the SAPClient.Commit() has finished ? In BAPI_TRANSACTION_COMMIT, it provides WAIT function. But NCO 2.0 can't add BAPI_TRANSACTION_COMMIT proxy class and SAPClient.CommitandWait() method was intentionally disabled. does anyone meet this problem, too ?
    Please tell me how to solve it.
    Thanks in advanced
    BTW, I already know I can wrapper BAPI_TRANSACTION_COMMIT. That's the way I don't want to do. Since it could result in Deadlock. I want to know is there any method that I can know the commit work has finished.

    Hi,
    Idealy, if the calling program could be automatically notified as soon as the commitwork is finished. Unfortunately, there is not such method and even not a method that is a little eleganter than polling, i.e., waiting and trying.
    Regards,
    Guangwei

  • 10 ms overhead when calling Thread.sleep on Linux

    Hi,
    I have been working on a traffic shaping simulation that requires me to send packets on a ms basis. When I call Thread.sleep(11) on Linux 2.4, I get a constant return around 30 ms. I tried to bypass the Thread.sleep function and called directly the select() function under linux with a timeout of 11 ms then I get a constant return around 20 ms. Then if I create a test.c program that loop 100 times calling the select(11), I get a very accurate rate around 10-11 ms. Anyone knows where that 10 ms overhead comes from? I tried executing the java program with Thread.sleep and the -XX:ForceTimeHighResolution but it doesn;t seem to change anything ! Any info would be very welcome ! Thanks

    Actually I get this behavior only on a machine with kernel 2.4. On a different machine with kernel 2.6 I get an accuracy of 10ms for a select call with 10 ms timeout. I know there was some improvements on the jiffy for kernel2.6 but I still don't get why calling select timeout 10ms from a C program return an accuracy of 10ms on linux 2.4 and the same select() timeout 10ms called from java return an accuracy of only 20 ms on kernel 2.4..... :( still looking

  • Replace the wait with java embedding thread.sleep() function

    Hi,
    How to replace the wait with java embedding thread.sleep() function. Can anyone help.
    Thanks.

    drag and drop the java embedding component
    include the following code in it.
    try{ 
    Thread.sleep(60000);
    }catch(Exception e)
    --Prasanna                                                                                                                                                                                                                                                                                                                           

  • Menu and Thread.sleep(5000) or Thread.currentThread.sleep(5000)

    Hi,
    I am using JMenu and switchable JPanels.
    When I click on a MenuItem the follownig code should starts
        cards.add(listenPanel,  "listenPanel");
        cardLayout.show(cards, "listenPanel");
        try{
          Thread.sleep(5000); //in ms
          PlayMP3Thread sound = new PlayMP3Thread("sound/ping.mp3");
        } catch(Exception e) {
          e.printStackTrace();
        }It seems to be what I want to reach, but it does not work the way I want it to.
    I would like the Panel to show right away, then wait 5s and then play the sound.
    BUT what it does is freez the unfolded menu for 5s, then plays the sound and after that it shows the new Plane.
    Can you tell me why this is??

    This might be what you want
    package tjacobs.thread;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Semaphore;
    import tjacobs.ui.Eyes;
    import tjacobs.ui.util.WindowUtilities;
    public class ThreadForMultipleAnytimeRuns extends Thread {
         private Runnable mRunnable;
         private Semaphore mSemaphore;
         public ThreadForMultipleAnytimeRuns(Runnable arg0) {
              super();
              init(arg0);
         private void init(Runnable r) {
              mRunnable = r;
              mSemaphore = new Semaphore(0);
              setDaemon(true);
         public ThreadForMultipleAnytimeRuns(Runnable arg0, String arg1) {
              super(arg1);
              init(arg0);
         public ThreadForMultipleAnytimeRuns(ThreadGroup arg0, Runnable arg1, String arg2) {
              super(arg0, arg2);
              init(arg1);
         public void run () {
              try {
                   while (!isInterrupted()) {
                        mSemaphore.acquire();
                        mRunnable.run();
              catch (InterruptedException ex) {}
         public void runAgain() {
              mSemaphore.release();
         public void runAgain(int numTimes) {
              mSemaphore.release(numTimes);
         public void stopThread() {
              interrupt();
         public int getSemaphoreCount() {
              return mSemaphore.availablePermits();
         public Runnable getRunnable() {
              return mRunnable;
         //The setRunnable method is simply not safe, and
         //trying to make it safe is going to effect performance
         //Plus I can't really see a gain in being able to set
         //The runnable on one of these threads. Just create
         //a new one!
         public synchronized void setRunnable(Runnable r) {
              if (getSemaphoreCount() > 0) {
                   try {
                        wait();
                   catch (InterruptedException ex) {
                        return;
              mRunnable = r;
         public static void main(String[] args) {
              final Eyes eyes = new Eyes(true);
              //eyes.addMouseMotionListener(eyes);
              Runnable r = new Runnable() {
                   public void run() {
                        eyes.blink();
                        try {
                             Thread.sleep(100);
                        catch(InterruptedException ex) {}
              final ThreadForMultipleAnytimeRuns ar = new ThreadForMultipleAnytimeRuns(r);
              ar.start();
              eyes.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent me) {
                        ar.runAgain();
              eyes.setPreferredSize(new Dimension(60,20));
              WindowUtilities.visualize(eyes);
    //          JFrame jf = new JFrame();
    //          jf.add(eyes);
    //          jf.pack();
    //          jf.setLocation(100,100);
    //          jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //          jf.setVisible(true);
    }

  • Thread yield() and sleep()

    what is the different bettween yield() and sleep() method
    in thread
    i think sleep() method make the called thread to wait then
    make the way to enter any other
    but yield() also do same but dont allow lower priority threads
    allow only higher priority thread.
    is this correct?

    Thread.yield() is used to give other threads a chance to get a processor time slice, according to the thread dispatcher rules. If there are no other threads ready to run, the current thread will gain the processor again.
    Thread.sleep() will always release the processor for at least the amount of time specified, even if there are no other threads requesting it.

  • My power button is pushed in so I have to wait till it goes to sleep and I can't turn it on with out pressing on the home button. I might need it fixed but I really don't want to have too much on my parents but I was wondering if I could do anything else?

    My power button doesn't work and I don't know what I can do without havin my parents spend a lot of money for the power button but I want to. No if their is any other way for me to fix it without damaging it and doing it carefully and I have an iPod touch 4th generation but I really want it to work again without having my iPod wait to go to sleep and its the white one and my brother says the white one isn't that good so ya... But I just want to know if theirs any other solution to this problem cause I'm getting really annoyed by it. Please help me! Thank you! :)

    - Make an appointment at the Genius Bar of an Apple store and hear what they hae to say. It is free.
    Apple Retail Store - Genius Bar                          
    you can turn on Assistive Touch it adds the Power and other buttons to the iPods screen. Settings>General>Accessibility>Assistive Touch

  • Servlet, threads and StaleConnectionException

    Hi folks,
    we're currently developing an J2EE application in which we have to works with threads started and stopped via web interface: on a test JSP page, we have a button to start the thread and another button to stop the same thread. At the moment, we have just one thread which periodically checks some data on a DB installed on the same machine on which the application server runs.
    The problem is, when the thread is restarted, a StaleConnectionException is thrown, which code SQL1224N The DB is DB2 from IBM and the application server is WebSphere 5; both of they run on a Linux Red Hat system.
    We use a JDBC Connection provided by the application server.
    We can't understand where is the problem. We suppose that the problem is creating independent threads from a servlet, as J2EE paradigm suggests not to do so. Is there anybody that encountered the same (or similar) problem ? Any suggestion ?
    Thanx a lot in advance.
    Claudio.

    Hi Claudio,
    hope this helps ...
    http://archive.midrange.com/java400-l/200301/msg00039.html
    WS App Throwing a StaleConnectionException
    Q: My WebSphere application is throwing a
    com.ibm.websphere.ce.cm.StaleConnectionException. What is the problem?
    This exception indicates that the connection is no longer valid. Here are some
    possible causes of it:
    1)The database management system is down.
    2)The application previously closed the connection.
    3)The connection has been orphaned, which means that the application has held
    the connection for too long without using it. The Data Source property "Orphan
    timeout" specifies the maximum number of seconds that an application can hold a
    connection without using it. If an app holds a connection without using it
    beyond the Orphan timeout value, WebSphere may return the connection to the
    connection pool. If the connection is returned to the connection pool, and the
    application then tries to use the connection, the Stale ConnectionException is
    thrown.

Maybe you are looking for