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)

Similar Messages

  • 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                                                                                                                                                                                                                                                                                                                           

  • Java Thread.sleep() on Windows 8 stops in S3 sleep status

    There's a desktop application that uses Thread.sleep() to achieve long (minutes or hours) delays. This same application has been working fine from Windows XP through Windows 7. The application calculates how far in the future it needs to do something, then hits a Thread.sleep(msToWait). This has been working fine, even if the system happens to go into S3 or S4 sleep state during the wait.  All is good as long as the machine is awake at the time when the sleep expires.
    As of Windows  8 (and 10), though, the code after Thread.sleep() does not execute "on time" if the machine has been in S3 during the sleep interval. It appears that the machine begins executing code at "msToWait" plus the time the machine has been in S3.
    Earlier versions of Windows did not exhibit this behavior; code after Thread.sleep() waited the right amount of time, irrespective of sleep status.
    A test program and procedure were developed. The procedure is to 1) run the program, 2) cause the machine to sleep for about a minute, then 3) wake the machine and wait for the program to finish.
    If this the program is run on Windows 10 (reporting as 8) with JVM Version: 25.40-b25, it fails (the 63589 corresponds to the minute that the machine was in S3):
    C:\Users\Tester\Downloads>SleepTester.exe
    Wed Apr 01 10:47:35 PDT 2015 Using default number of minutes: 5
    Wed Apr 01 10:47:35 PDT 2015 You can use "SleepTester -minutes 10" to have it sleep for 10 minutes, for example.
    Wed Apr 01 10:47:35 PDT 2015 JVM Version: 25.40-b25 Windows Version: Windows 8
    Wed Apr 01 10:47:35 PDT 2015 The program will now wait for 5 minutes.  Expect wrap-up at Wed Apr 01 10:52:35 PDT 2015
    Wed Apr 01 10:53:38 PDT 2015 The system has come through the Thread.sleep(300000).
    Wed Apr 01 10:53:38 PDT 2015 This should be a low number: 63589
    Wed Apr 01 10:53:38 PDT 2015 This appears to be operating incorrectly...the expected sleep time has NOT been achieved.
    Wed Apr 01 10:53:38 PDT 2015 Program is ending.
    If the process is run on Windows 7, it does not fail:
    Wed Apr 01 17:12:18 EDT 2015 Java Runtime Version: 1.8.0_31-b13 JVM Version: 25.31-b07 Windows Version: Windows 7
    Wed Apr 01 17:12:18 EDT 2015 The program will now wait for 6 minutes.  Expect wrap-up at Wed Apr 01 17:18:18 EDT 2015
    Wed Apr 01 17:18:18 EDT 2015 The system has come through the Thread.sleep(360000).
    Wed Apr 01 17:18:18 EDT 2015 This should be a low number: 0
    Wed Apr 01 17:18:18 EDT 2015 Program is ending.
    This is the guts of  test program:
    [code]
    public static void main(String[] args) throws Exception {
       System.out.println(new Date() + " Java Runtime Version: " + System.getProperty("java.runtime.version") + " JVM Version: " + System.getProperty("java.vm.version") + " Windows Version: " + System.getProperty("os.name"));
       long msDelay = mMinutes * 60 * 1000;
       long wakePoint = new Date().getTime() + msDelay;
       System.out.println(new Date() + " The program will now wait for " + mMinutes + " minutes. Expect wrap-up at " + new Date(wakePoint));
       Thread.sleep(msDelay); // If the machine goes into S3 during this interval, it should not matter, as long as it's awake when it fires.
       System.out.println(new Date() + " The system has come through the Thread.sleep(" + msDelay + "). ");
       long msAccuracy = Math.abs(new Date().getTime() - wakePoint);
       System.out.println(new Date() + " This should be a low number: " + msAccuracy);
       if (msAccuracy > 1000) System.out.println(new Date() + " This appears to be operating incorrectly...the expected sleep time has NOT been achieved.");
       System.out.println(new Date() + " Program is ending.");
    [/code]
    Was the change in behavior from earlier versions of Windows intentional?  Is it something that the JVM is controlling, or is there a difference in the underlying OS that is beyond the control of the JVM?

    I might need to create a work-around whereby I maintain a watch of the msDelay and the system clock.  If there is a discontinuity (which would only happen on Windows 8 or higher), then I would repair the msDelay value.
    A separate (but related) question:
    Can I conclude that since older JVM's running on Windows 8 still have the problem, that it's a Windows issue, and not a JVM issue?

  • 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.

  • Java Thread.sleep(timeout) is influenced by changes to System time on Linux

    Java Thread.sleep(timeout) is influenced by changes to System time on Linux
    bugId : 6311057
    I encountered this problem in redhat6/ jdk 1.6

    890651 wrote:
    Java Thread.sleep(timeout) is influenced by changes to System time on Linux
    bugId : 6311057
    I encountered this problem in redhat6/ jdk 1.6At least half the time I use it, I'd want it to be, the other half I wouldn't care.
    What are you doing with it where this might be a problem?
    Changing the system clock abruptly can cause all kinds of problems with your system anyway, because various background activities etc. often depend on file dates. Wherever possible use the "skew" method to adjust your system clock, rather than just plonking in a new value, especially if you are setting the clock backwards.

  • Can LabVIEW threads sleep in increments less than a millisecon​d?

    I am aware of two LabVIEW sleep functions:
    1) All Functions | Time & Dialog | "Wait (ms)"
    2) All Functions | Time & Dialog | "Wait Until Next ms Multiple"
    In this day and age, when 3GHz processors sell for less than $200, it seems to me that a millisecond is an eternity. Is there any way to tell your LabVIEW threads to sleep for something less than a millisecond?
    In Java, the standard Thread.sleep() method is written in milliseconds [sorry, the bulletin board software won't let me link directly]:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long)
    but there is a second version of the method that allows for the possiblity of nanoseconds:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/​Thread.html#sleep(long, int)
    So there does seem to be some consensus that millisecond sleep times are getting a little long in the tooth...

    Hi Tarheel !
    May be you should get some idea of the kind of timing accuracy that you can reach when using a loop.
    Use the attached vi, which runs repeatedly a For loop (10 iterations) reading the time, then calculate the average and standard deviation of the time difference between the loop iterations.
    On my PC (P4, 2.6 MHz, W2K), I get a standard deviation of about 8 ms, which appears to be independent of the sleep duration I asked for.
    Same thing with a timed loop.
    Under MacOS X (PowerBook, 1.5GHz), the SD falls down to 0.4 ms.
    I tried to disable most of the background processes running on my PC, but I could not get a better resolution.
    Seems that the issue is not in LV but on the way the OS manage its internal reference clock.
    Since you are a Java afficionado, may be you could produce something equivalent ?
    A proof that nanosecond resolution is available on a PC could be of great help to NI. Why bother with costly timers on DAQ cards ?
    By the way, it took me about one minute to create the attached vi. I would like to have an idea of the time required to do the same thing in Java.
    Tempus fugit...
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Timing precision.zip ‏11 KB

  • Work manager using thread.sleep or delay doesn't work

    Hi all,
    I used Spring framework and oracle weblogic 10.3 as a container.
    I used workmanager for manage my thread, I already made one thread that managed by workmanager. Fortunately spring provide the delegation class for using workmanager, so I just need to put it on applicationContext.xml.
    But when I put the "while" and TimeUnit for sleep the process on desired delayed time, the deployment process never finished. It seems the deployment process never jump out from while loop for finishing the deployment.
    Why?, As I know using typical thread, there is no issue like this. Should I use another strategy for make it always loop and delay.
    This is my simple code :
    import java.util.concurrent.TimeUnit;
    import org.springframework.core.task.TaskExecutor;
    public class TaskExecutorSample{
         Boolean shutdown = Boolean.FALSE;
         int delay = 8000;
         TimeUnit unit = TimeUnit.SECONDS;
         private class MessageGenerator implements Runnable {
              private String message;
              public MessageGenerator(String message){
                   this.message = message;
              @Override
              public void run() {
                   System.out.println(message);
         private TaskExecutor taskExecutor;
         public TaskExecutorSample(TaskExecutor taskExecutor){
              this.taskExecutor = taskExecutor;
              try {
                   while (shutdown.equals(Boolean.FALSE)){
                        this.printMessage();
                        unit.sleep(delay);
              } catch (Exception e) {
                   System.out.println(e.getMessage());
         public void printMessage() {
              taskExecutor.execute(new MessageGenerator("Print this Messages"));
    Really thanks in advance.
    Regards,
    Kahlil
    Edited by: Kahlil on May 26, 2010 2:38 PM
    Edited by: Kahlil on May 26, 2010 2:42 PM

    Hi,
    i m not sure whether it's an issue with Spring or not. But i tried using Thread.sleep(1000) in a Simple webapplication to see Workmanagers works properly or not. I found that it works extremely great: http://weblogic-wonders.com/weblogic/2010/01/24/workmanager-at-webapplication-level/
    Thanks
    Jay SenSharma

  • Problem with Thread.sleep()

    hi all,
    I am trying Thread.sleep() method to introduce a delay. In the program i ask the user to specify the value to be entered in Thread.sleep() (to indicate the amount of delay desired by the user). but strangely, if a low value is entered, i get a different result which actually should not happen as the rest of the calculation remains the same, only the amt of delay changes.
    could anyone help me with this
    cheers
    ankit

    [url http://forum.java.sun.com/thread.jsp?forum=31&thread=536288]Double-post

  • Using Thread.sleep()

    When I put Thread.sleep() in my code, the debugger says I need to catch it. How do I do that?

    But in general, you don't want to just smother exceptions like that. It's okay when you're sleeping (or can be) because often if you're interrupted, you want to just ignore it and move on. However, there's more to handling exceptions than just an empty catch block.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • Non-static version of java.lang.Thread.dumpstack?

    hi,
    it would be useful sometimes to have a graphical debug panel on an application I'm working on which shows the active threads and allows further information to be shown if wanted - the problem is that I can't find an API call to get the current stack dump of an arbitrary thread - does anyone know if this is possbile somehow without a full debug environment?
    java.lang.Thread.dumpstack would be ideal if only it were an instance method..
    thanks,
    asjf

    what's the probelm? you call this in the threads class
    and each thread (object) executes this statement and
    therefore prints its stacktrace ...ok - here is some mocked up (and plain wrong in terms of the tree model's consistency over sequential method calls) code that shows what I'd like to achieveimport java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import javax.swing.event.*;
    public class JThreadExp extends JPanel {
       JTree tree;
       JTextArea jta;
       public JThreadExp(TreeModel model) {
          super(new GridLayout(1,2,4,4));
          tree = new JTree(model);
          jta = new JTextArea();
          add(tree);
          add(jta);
          tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
                PrintStream stderr = System.err;
                String msg=null;
                try {
                   TreePath tp = e.getPath();
                   System.out.println(tp.getLastPathComponent());
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   PrintStream ps = new PrintStream(new BufferedOutputStream(baos, 1024*1024));
                   System.setErr(ps);
                   Thread t = (Thread) tp.getLastPathComponent();
                   try {
                      t.dumpStack();
                   } catch(Throwable ee) {}
                   ps.close();
                   jta.setText(baos.toString()); //newXML.toString());
                } catch(Exception e2) {
                   msg = e2.getMessage();
                System.setErr(stderr);
                if(msg!=null)
                   System.out.println(msg);
       public static void main(String[]arg) throws Exception {
          JFrame frame = new JFrame("JThreadExp");
          JThreadExp jte;
          final ThreadModel tm = new ThreadModel();
          frame.getContentPane().add(jte = new JThreadExp(tm));
          frame.pack();
          frame.setVisible(true);
          final JTree tree = jte.tree;
          new Thread(new Runnable() {
             public void run() {
                try {
                   while(true) {
                      TreeModelEvent tme = new TreeModelEvent(this, new Object [] {tm.getRoot()});
                      for(Iterator i = tm.listeners.iterator(); i.hasNext(); )
                         ((TreeModelListener) i.next()).treeStructureChanged(tme);
                      Thread.sleep(5000);
                      new Thread(new Runnable() {
                         public void run() {
                            try { Thread.sleep(50000); } catch(Exception e) {e.printStackTrace();}
                      } ).start();
                } catch(Exception e) {
                   e.printStackTrace();
          } ).start();
    class ThreadModel implements TreeModel {
       public boolean isLeaf(Object node) { return (node instanceof Thread); }
       public Object getRoot() {
          ThreadGroup uppermost = Thread.currentThread().getThreadGroup();
          while(uppermost.getParent()!=null)
            uppermost = uppermost.getParent();
          return uppermost;
       public Object getChild(Object p, int i) {
          Object result = "<unavailable>";
          if(p instanceof ThreadGroup) {
             ThreadGroup parent = (ThreadGroup) p;
             ThreadGroup[] tg = new ThreadGroup[parent.activeGroupCount()];
             Thread[] t = new Thread[parent.activeCount()];
             parent.enumerate(tg, false);
             parent.enumerate(t, false);
             if(i<tg.length)
                result = tg;
    else if(i<tg.length+t.length)
    result = t[i-tg.length];
    return result;
    public int getChildCount(Object node) {
    int result = 0;
    if(node instanceof ThreadGroup) {
    ThreadGroup parent = (ThreadGroup) node;
    ThreadGroup[] tg = new ThreadGroup[parent.activeGroupCount()];
    Thread[] t = new Thread[parent.activeCount()];
    result += parent.enumerate(tg, false);
    result += parent.enumerate(t, false);
    return result;
    public int getIndexOfChild(Object parent, Object child) {
    for(int i=0; i<getChildCount(parent); i++) {
    if(getChild(parent,i).equals(child))
    return i;
    return -1;
    Set listeners = new HashSet();
    public void addTreeModelListener(TreeModelListener l) {
    listeners.add(l);
    public void removeTreeModelListener(TreeModelListener l) {
    listeners.remove(l);
    public void valueForPathChanged(TreePath path, Object newValue) { // this shouldn't be called - Tree is not editable
    System.out.println("valueForPathChanged");
    } The problem is that I'd like to obtain a reference to a Thread object (which I haven't written the code for) and get a (vaguely accurate if not exact) stack dump from it.
    I'll have a look over JDB in the meantime thanks :)
    thanks,
    asjf

  • What is an alternate to Thread.Sleep()?

    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?

    watwatacrazy wrote:
    What is an alternate to thread.sleep? The reason being, my action listener won't let me throw exceptions so I need an alternative to thread.sleep, anything?I am in no way condoning this idea, because as mentioned it is a very bad idea.
    However. Not lettiing you throw exceptions is not a reason to not do something. All it means is that you need a catch block. You should review the exceptions part of the Java tutorial found here [_Java Tutorial : Exceptions_|http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]

  • 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.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...

  • $ENV perl equivalent in Java

    We are in our first steps in trying to convert some of our systems from Perl to Java.
    In a module we had (Database module) which was responsible for all DB activity, we had an area where, upon errors, we printed out $ENV{SCRIPT_NAME} environment variable, which is set by Apache and can be read by Perl. This helps us debug things by knowing which script was ran when a DB error occurred.
    As we are porting the Database module into a Database class, we are trying to think how we can achieve the same capability with Java.
    I don't know of the existence of $ENV equivalent in Java. Not one that contains the web-server executed script, in case its a script that is ran by a web server.
    Is there?
    Note that the Database module may be ran as part of a Servelet but may also be part of just a simple server script. In perl, is such case, the $ENV{SCRIPT_NAME} would come out empty.
    Any suggestions of how to do that?

    Pidgin wrote:
    As you indicated: Note that both are relatively slow and should only be used for exceptional or error conditions.
    The access to the SCRIPT_NAME is actually a web re,ated variable that we need for showing which HTTP resquest generated the specific SQL error.It's only a variable in perl (or in CGI scripts, to be more precise).
    It happens often enough, and doing a very low-level trace of the executed code migt not be the right option.SQLExceptions that need logging happen often? That shouldn't be the fact. How often?
    Stacktraces are not awfully slow. They are ok for handling errors & exceptions. But they should not be used for classical flow control.
    For example, it might be that the executing code is Script.class using Database.class, but Script.class can be initiated from www.whatever.com/script/ or www.whatever.com/premium/script/.. in each case, we want to know the full URL of the called "script'.With the stack trace you'd see the Servlet and/or Action that handles the request.
    So we do need access to the web "environment".
    What we do now, is store a static Servlet_Request variable (set on the first Database constructor, by passing the servlet request and response objects to the Database constructor). From that point on, we can access Servlet_Request.getRequestURI()That won't work as soon as more than one request is handled at the same time (which is very, very soon!).
    You might want to look into something like log4js MDC, where you can at one point in your application set a key in a map and have that appear in every log statement from that thread until it's removed again.
    This is quite different than the Perl logic, where we could access a "web enabled" System.getenv() and read from it SCRIPT_NAME or other web related parameters, if they existed (or returning null if they didn't)You should not try to apply the best practices learned by perl web programming 1:1 on Java. In the Java world pretty different concepts apply, especially when doing Web-Programming, as Perl web-applications are usually based on the rather antiquated CGI interface, while Java uses a central application server that handles each request as it wishes.

  • Question on java.lang.Thread "starting problems"

    hi everybody
    i've just little trouble running a tiny program which uses Threads.
    maybe there's a misunderstanding from my side:
    About my code:
    01  public class MyThread extends Thread {
    02
    03    String any_string = null;
    04
    05    public MyThread(String param) {
    06      any_string = param;
    07      this.start();
    08    }
    09
    10    public void run() {
    11      while(!isInterrupted()) {
    12        System.out.println(" > This Thread is running!");
    13        // any other operation...
    14        try {
    15        sleep(1000);
    16      }
    17      catch(Exception e) {}
    18    }
    19  }This is a Thread's code similar to those you can find it in the java.lang.Thread Documentation or in the java Tutorial.
    In my example I got a IllegalThreadStateException in codeline 07 which means (compare to java.lang.Thread Documentation) that the code tries to start the Thread while the Thread is still running.
    I always thought a Thread will not start itself.
    I thought (and that's the way, i red it in the documentation) that the constructor of a Thread only allocates the new Thead-Object.
    But by constructing MyThread I got the descripted exception (i'm beginning to repeat myself...). The "funny" thing on this exception is that the Thread at least IS running but there could be no Object allocated
    01  ...
    02  /**
    03   * construction of a new Object of the class MyThread.
    04   * test will be auto-started by the MyThread constructor
    05   */
    06  MyThread test = new MyThread("any-string");
    07  ...
    08  test.anyMethodOfClassMyThread();This little code generates a java.lang.NullPointerException in line 08 (when trying to access the object of class MyThread). Even after the application exits (in case of this exception), the run()-Method of MyThread generates its Text-Output " > This Thread is running!". argh
    Does anyone see my mistake / misunderstanding??
    It's really frustrating if you are sitting in front of your pc and can't get the reason why your prog is generating that "bullshit" (ok... i know - it's only generatting the bullshit I told it to generate :( )
    Any suggestions or ideas
    thanks,
    Thof

    Well now, I don't get a NullPointerException, when I try to call a method of MyThread. Here's your code, with slight modifications by me:
    public class MyThread extends Thread {
        String any_string = null;
        public MyThread(String param) {
            any_string = param;
            this.start();
        public String getAnyString(){
            return any_string;
        public void run() {
            while(!isInterrupted()) {
                System.out.println(" > This Thread is running!");
                try {
                    sleep(1000);
                catch(Exception e) {}
    }To test the app I wrote this class:
    public class TestMyThread {
        public static void main(String[] args) {
            MyThread temp = new MyThread("Hello World");
            System.out.println(temp.getAnyString());
    }Now it does print out the correct "Hello World".
    Your other problem of the thread not shutting down is because it is not a daemon thread. To solve this you will need to add this Thread to a ThreadGroup and set the ThreadGroup as a Daemon group. (see ThreadGroup::setDaemon() )
    Or you can put a little boolean in your while loop and break out when you change the value of the boolean. Then when you want to shut down you simply change the boolean
    Hope this helps
    -Philip

Maybe you are looking for

  • I have Mac osx 10.5.8 and tried to upgrade firefox , now it won't work at all even my old firefox won't work

    I need to be able to go back to my old version of firefox or get this one to work

  • Newbie in XML

    Hi All, i have just started with java xml programming. I am trying to parse a simple document using DOM parser, and i have a few doubts. My xml file is : ========= <?xml version="1.0"?> <personal_info> <!-- This sample document contains my personal i

  • Opening linked documents in separate browser tabs

    How can I configure Adobe Reader to open a secondary PDF in a new tab from a primary PDF instead of the secondary replacing the primary in the same tab/window? If I use Foxit Reader with the same PDFs and the same IE the links from the primary PDF op

  • OWB Repository Install Question

    Hi all I am assigned to oracle ERP project and owb has to be installed for bis/edw. at the owb 2.x version, when repository install , following menu appeared 'which operation would you like to perform ? create a new BIS Repository Drop an existing BI

  • Updating multiple rows at a time

    Dear buddies, I am trying to update a couple of columns for multiple rows. This is my SQL: update department b set (b.departmentid, b.departmentmaster2) =     (select a.departmentid, a.status      from departmentmaster a      where trim(a.description