5 Replies Latest reply: Aug 2, 2011 11:15 AM by DrClap RSS

    Is it guaranteed a started thread will run to completion?

    869679
      Hi guys,

      Someone wrote me this about threads:

      "Thread running depends on the VM Scheduler and *there is NO guaranteed a Thread will run and pick by the VM Scheduler despite you have started the Thread with a call x.start()*. When you started the Thread it's just in a RUNNABLE STATE, reread the chapter until you fully understood" (Chapter 9 Thread - Sun Certified Programmer for Java 6 - Study Guide (310-065) - Kathy Sierra and Bert Bates - 2008)

      It is the red sentence that make me really confused. Actually, I read that chapter several times, and I could not read this kind of affirmation in all the chapter. What I could read is this,

      From the book (pages 713 and 714)

      class NameRunnable implements Runnable { 
      public void run() { 
      for (int x = 1; x <= 3; x++) { 
      System.out.println("Run by "
      + Thread.currentThread().getName()
      + ", x is " + x);
      }
      }
      }

      public class ManyNames { 
      public static void main(String [] args) { 
      // Make one Runnable
      NameRunnable nr = new NameRunnable();
      Thread one = new Thread(nr);
      Thread two = new Thread(nr);
      Thread three = new Thread(nr);
      one.setName("Fred");
      two.setName("Lucy");
      three.setName("Ricky");
      one.start();
      two.start();
      three.start();
      }
      }


      And the authors wrote this:

      Nothing is guaranteed in the preceding code EXCEPT this:

      Each thread will start, and each thread will run to completion.

      I try to explain myself, what I understood from the sentence in the book: "Each thread will start, and each thread will run to completion "

      $java ManyNames

      After this call, main method from the class ManyNames is invoked and the JVM execute the code in that method sequentially. When the main thread calls one.start(), the one thread (Java thread) is mapped with an Operative System thread (well, in most implementations), but the important thing, the one thread (Java thread) gets the RUNNABLE state waiting for a chance to get the RUNNING state an start the execution of the run() method of its target Runnable. So, at this point we have two thread that can be chosen to get the RUNNING state, main thread and the thread one. Assume main thread executes main method to the end. In this case, the calls two.start() and three.start() are invoked. Main thread finishes, and we have three alive threads waiting for its turn to get the RUNNING state. For me run to completion means that all these threads will print three times the sentence:

      "Run by [THREAD NAME: Fred, Lucy or Ricky], x is [1, 2 or 3]"

      And all of them will finish their run() method (AS THE CODE STANDS). One possible output could be:
      Run by Fred, x is 1
      Run by Lucy, x is 1
      Run by Lucy, x is 2
      Run by Fred, x is 2
      Run by Lucy, x is 3
      Run by Fred, x is 3
      Run by Ricky, x is 1
      Run by Ricky, x is 2
      Run by Ricky, x is 3

      But this order is not guaranteed.

      So, my question is simple, if we execute THIS CODE (without any changed) in ANY Java Virtual Machine, is it GUARANTEED that all started threads (main thread, Fred, Lucy and Ricky) will run to completion OR I have to believe what the guy wrote me: there is NO guaranteed a Thread will run and pick by the VM Scheduler despite you have started the Thread with a call x.start()?

      If what this guy said is correct, is it worth create and start a thread if there are not guaranteed that this thread will run to completion? Well, if it is a nice visual clock on the screen it does not matter if we can see the clock or not, but how about if it is a thread that control the emergency process in a factory, just an example.


      Thanks for your opinions,

      Alvaro

      Edited by: Alvaro on Jul 28, 2011 5:15 PM
        • 1. Re: Is it guaranteed a started thread will run to completion?
          802316
          While it is not guaranteed, the purpose of starting threads is that it will run to completion, and this is what happens under normal operating conditions.
          • 2. Re: Is it guaranteed a started thread will run to completion?
            869679
            Thanks for your answer.

            Finally, I have understood it. Just to give more information about the topic:

            As K&S wrote in their study guide:

            Don't make the mistake of designing your program to be dependent on a particular implementation of the JVM. As you'll learn a little later, different JVMs can run threads in profoundly different ways. For example, one JVM might be sure that all threads get their turn, with a fairly even amount of time allocated for each thread in a nice, happy, round-robin fashion. But in other JVMs, a thread might start running and then just hog the whole show, never stepping out so others can have a turn. If you test your application on the "nice turn-taking" JVM, and you don't know what is and is not guaranteed in Java, then you might be in for a big shock when you run it under a JVM with a different thread scheduling mechanism.

            As Paul Clapham answered me in JavaRanch:

            If your application starts a thread, then the operating system will execute that thread according to its rules. Which normally means that the thread will start running right away. But it's possible that the operating system is already running several threads which have higher priority than yours, so it won't start running your thread right away. Eventually your thread will run, when those higher-priority threads have gone away, but there isn't any guarantee about how long that will take. It could be seconds, or hours, or weeks, or longer.

            Yes, it's guaranteed that a thread will run. But it isn't guaranteed when that will happen, and it might never happen.


            So, the answer is NO.

            Check, this thread for more info:

            http://www.coderanch.com/t/546711/java-programmer-SCJP/certification/Will-started-thread-run-completion#2481151
            • 3. Re: Is it guaranteed a started thread will run to completion?
              jschellSomeoneStoleMyAlias
              Alvaro wrote:
              Thanks for your answer.

              Finally, I have understood it. Just to give more information about the topic:

              As K&S wrote in their study guide:

              Don't make the mistake of designing your program to be dependent on a particular implementation of the JVM. As you'll learn a little later, different JVMs can run threads in profoundly different ways. For example, one JVM might be sure that all threads get their turn, with a fairly even amount of time allocated for each thread in a nice, happy, round-robin fashion. But in other JVMs, a thread might start running and then just hog the whole show, never stepping out so others can have a turn. If you test your application on the "nice turn-taking" JVM, and you don't know what is and is not guaranteed in Java, then you might be in for a big shock when you run it under a JVM with a different thread scheduling mechanism.
              I doubt that is going to happen on a modern desktop OS.

              I suppose it might happen on a mobile/cell VM but then you should be targeting that VM anyways and not all VMs.

              >
              As Paul Clapham answered me in JavaRanch:

              If your application starts a thread, then the operating system will execute that thread according to its rules. Which normally means that the thread will start running right away. But it's possible that the operating system is already running several threads which have higher priority than yours, so it won't start running your thread right away. Eventually your thread will run, when those higher-priority threads have gone away, but there isn't any guarantee about how long that will take. It could be seconds, or hours, or weeks, or longer.
              Really, really unlikely.

              If that was true then you couldn't start your JEE server with any assurance that it would ever do anything.
              Given that there are tens if not hundreds of thousands of JEE servers that certainly isn't the case.

              For normal processing scenarios if none of your threads run then there is something wrong with the environment. It has nothing to do with your design nor implementation.
              • 4. Re: Is it guaranteed a started thread will run to completion?
                EJP
                As K&S wrote in their study guide:
                But in other JVMs, a thread might start running and then just hog the whole show, never stepping out so others can have a turn.
                This is only true of 'hard real-time' operating systems with completely pre-emptive scheduling. I doubt that it would be even possible to implement a JVM and the JDK correctly on such a system, and you certainly won't encounter such an OS outside RTSJ which is another whole ballgame from the standard JVM. It would also require the higher-priority thread never to do any I/O or sleeps or waits. 99.9999% of all threads you are ever going to encounter do all those things very frequently indeed.
                As Paul Clapham answered me in JavaRanch:

                ... Eventually your thread will run, when those higher-priority threads have gone away
                I'm surprised at DrClap. This statement is completely incorrect. A lower-priority thread can run any time all higher-priority threads are either blocked, e.g. doing I/O, or sleeping (Thread.sleep()), or in Object.wait(), or scheduled out for fairness reasons. You certainly don't have to wait for them all to go away.
                It could be seconds, or hours, or weeks, or longer.
                This also is completely incorrect. Any operating system other than a hard real-time operating system with completely pre-emptive scheduling will give your threads a run basically some time in just about every second.
                • 5. Re: Is it guaranteed a started thread will run to completion?
                  DrClap
                  EJP wrote:
                  ... Eventually your thread will run, when those higher-priority threads have gone away
                  I'm surprised at DrClap. This statement is completely incorrect. A lower-priority thread can run any time all higher-priority threads are either blocked, e.g. doing I/O, or sleeping (Thread.sleep()), or in Object.wait(), or scheduled out for fairness reasons. You certainly don't have to wait for them all to go away.
                  You have to take into account the fact that I was answering the question in the context of one of those certification exams. And so there's no connection to real life or anything like that. The questioner was obsessing over two statements about threads which appeared to contradict each other, but only if you used an extremely absolutist definition of the term "guaranteed".

                  So I don't apologize for those statements, incorrect as they may have been. At least they were closer to real life than some slogan which people are supposed to memorize to get a bit of paper. And it doesn't seem that long since I used an operating system where high-priority compute-bound threads could prevent lower-priority threads from running forever, although things are arranged better these days.