In JAVA, when it comes to threads, very little is guaranteed

In JAVA, when it comes to threads, very little is guaranteed OCP OCA

As a JAVA developer, you must know what is and what is not guaranteed, before you can write decent multithreaded code. As a brief summary:

  • There is nothing in the Java specification that says threads will start running in the order in which they were started.
  • There is no guarantee that once a thread starts executing, it will keep executing until it’s done.

So nothing is guaranteed in the following code

package eu.albertomorales.OCAOCP.threads.example1; 
public class Example1 { 
   private void doIt() { 
      Runnable myRunnable = new Runnable() { 
         @Override public void run() { 
            for (int n = 0; n < 10; n++) {                          
                  .getName()+" says "+n); 
      Thread myThrea1d = new Thread(myRunnable, "FIRST");          
      Thread myThread2 = new Thread(myRunnable, "SECOND"); 
      Thread myThread3 = new Thread(myRunnable, "THIRD"); 
   public static void main(String[] args) { 
      Example1 example1 = new Example1(); 

except this:

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

This is a capture of the standard output (remember, this is just one of the possible output we can get, for the particular JVM implementation I’m using to ilustrate this post):

FIRST says 0
FIRST says 1
FIRST says 2 
FIRST says 3 
FIRST says 4 
FIRST says 5 
THIRD says 0 
THIRD says 1 
THIRD says 2 
THIRD says 3 
THIRD says 4 
THIRD says 5 
THIRD says 6 
THIRD says 7 
THIRD says 8 
THIRD says 9 
SECOND says 0 
SECOND says 1 
SECOND says 2 
SECOND says 3 
SECOND says 4 
SECOND says 5 
SECOND says 6 
SECOND says 7 
SECOND says 8 
SECOND says 9 
FIRST says 6 
FIRST says 7 
FIRST says 8 
FIRST says 9`

As you can notice:

  • “FIRST” is started first and it starts running first, but it finishes last.
  • “SECOND” is started before “THIRD”, but “THIRD” starts running before “SECOND”.
  • “FIRST” go to “sleep” with no reason within a loop, and it gives “SECOND” and “THIRD” a chance to run. But “THIRD” doesn’t do so: once “THIRD” stars executing, it keeps executing until it’s done.

Surprised? if so, probably you’re not familiar with threads. To be aware of what is and is not guaranteed behavior is a must if you want to design your program in such a way that it will work, regardless of the underlying JVM.

Would you like to share another example? Have you got an interesting one, and would you like to share it with the comunity? If so, or you’re interested in receiving more information, please post them in the comments so we can write about it, and we can keep in touch!

And as always, if you’ve liked this post, you can Tweet it. Thank you.

Alberto Morales Morales

Software craftsman. Passion for developing quality code that can be proud of. Happily married.

Madrid, Spain.