Java Thread Priority Example

In Java, every thread has a priority assigned to it. Whether you have explicitly assigned one or not. By default, a java thread inherits the priority (implicit) of its parent thread. Using the setPriority() method you can increase or decrease the thread priority of any java thread. You can set the priority of java threads using numeric values from (1 through 10) or use the predefined static constants Thread.MIN_PRIORITY (1), Thread.MAX_PRIORITY (10), or default priority of Thread.NORM_PRIORITY (5).

Thread Priority Behavior

Typically, in the Java JVM the highest priority threads continue running until the following occurs:

  • The Thread yields by calling the yield() method
  • it calls sleep() method
  • it ceases to be runnable because of blocking for I/O
  • a higher priority thread has become runnable, and begins running

Note

The thread priorities defined in the Java Thread API are merely scheduling hints. The mapping of Java’s 10 priority levels are platform specific, so it is conceivable that two or more Java priorities can map to the same OS priority on one system and different Operating System (OS) priorities on another. Some OSs have fewer than ten priority levels, which would result in multiple Java priorities mapping to the same OS priority.

According to “Java Concurrency In Practice“, using thread priorities can lead to liveness problems:

Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.

My Observations on using Thread Priorities

I have noticed that Thread priorities work on most operating systems but they I have noticed that it seems to have minimal impact. Accordingly, priorities help to order the threads that are in the run queue and will not change the order that the threads are being run in any major way.

According to Cay S. Horstmann:

CAUTION

Some platforms (such as Windows NT) have fewer priority levels than the 10 levels that the Java platform specifies. On those platforms, no matter what mapping of priority levels is chosen, some of the 10 JVM levels will be mapped to the same platform levels. In the Sun JVM for Linux, thread priorities are ignored altogether, so you will not be able to see the “express threads” in action when you run the sample program at the end of this section.

Note

Windows implements a thread fallback mechanism whereby a thread that has not had a chance to run for a long time is given a temporary priority boost.

MyPriorityExample.java

package com.avaldes.tutorials;

public class MyPriorityExample {

  public static void priorityTest() {
    Thread t1 = new Thread(new MyRunnableThread(), "Priority_10");
    Thread t2 = new Thread(new MyRunnableThread(), "Priority_8");
    Thread t3 = new Thread(new MyRunnableThread(), "Priority_6");
    Thread t4 = new Thread(new MyRunnableThread(), "Priority_4");
    Thread t5 = new Thread(new MyRunnableThread(), "Priority_2");
    
    t1.setPriority(10);
    t2.setPriority(8);
    t3.setPriority(6);
    t4.setPriority(4);
    t5.setPriority(2);

    t1.start();
    t2.start();
    t3.start();   
    t4.start();   
    t5.start();   
  }
  
  public static void main(String[] args) {
    priorityTest();
  }
}

MyRunnableThread.java

package com.avaldes.tutorials;

public class MyRunnableThread implements Runnable {
  private int counter = 0;
  
  public synchronized void increment() {
    counter++;
  }
  
  @Override
  public void run() {
    while (counter < 5) {
      System.out.format("%s, counter at %d\n", Thread.currentThread().getName(), counter);
      increment();
    }
  }
}

Observations on Several Runs

As you can see from the three successive program runs I performed, I do not see any consistency by using thread priorities as would be expected when using Windows Operating System.

Output #1

Priority_10, counter at 0
Priority_2, counter at 0
Priority_8, counter at 0
Priority_6, counter at 0
Priority_4, counter at 0
Priority_6, counter at 1
Priority_8, counter at 1
Priority_2, counter at 1
Priority_10, counter at 1
Priority_10, counter at 2
Priority_10, counter at 3
Priority_10, counter at 4
Priority_2, counter at 2
Priority_2, counter at 3
Priority_2, counter at 4
Priority_8, counter at 2
Priority_8, counter at 3
Priority_8, counter at 4
Priority_6, counter at 2
Priority_4, counter at 1
Priority_6, counter at 3
Priority_6, counter at 4
Priority_4, counter at 2
Priority_4, counter at 3
Priority_4, counter at 4

Output #2

Priority_8, counter at 0
Priority_8, counter at 1
Priority_2, counter at 0
Priority_4, counter at 0
Priority_10, counter at 0
Priority_6, counter at 0
Priority_10, counter at 1
Priority_4, counter at 1
Priority_2, counter at 1
Priority_8, counter at 2
Priority_2, counter at 2
Priority_4, counter at 2
Priority_10, counter at 2
Priority_6, counter at 1
Priority_10, counter at 3
Priority_10, counter at 4
Priority_4, counter at 3
Priority_2, counter at 3
Priority_8, counter at 3
Priority_2, counter at 4
Priority_4, counter at 4
Priority_6, counter at 2
Priority_6, counter at 3
Priority_8, counter at 4
Priority_6, counter at 4

Output #3

Priority_10, counter at 0
Priority_6, counter at 0
Priority_2, counter at 0
Priority_2, counter at 1
Priority_2, counter at 2
Priority_2, counter at 3
Priority_2, counter at 4
Priority_4, counter at 0
Priority_4, counter at 1
Priority_4, counter at 2
Priority_4, counter at 3
Priority_4, counter at 4
Priority_8, counter at 0
Priority_8, counter at 1
Priority_8, counter at 2
Priority_8, counter at 3
Priority_8, counter at 4
Priority_6, counter at 1
Priority_6, counter at 2
Priority_6, counter at 3
Priority_6, counter at 4
Priority_10, counter at 1
Priority_10, counter at 2
Priority_10, counter at 3
Priority_10, counter at 4

Related Posts

  • Java Thread, Concurrency and Multithreading Tutorial
    This Java Thread tutorial will give you a basic overview on Java Threads and introduce the entire tutorial series on concurrency and multithreading. From here, you will learn about many java thread concepts like: Thread States, Thread Priority, Thread Join, and ThreadGroups. In addition, you will learn about using the volatile keyword and examples on using wait, notify and notifyAll.
  • Java Thread States - Life Cycle of Java Threads
    Get a basic understanding of the various thread states. Using the state transition diagram we show the various states for a Java thread and the events that cause the thread to jump from one state to another.
  • Creating Java Threads Example
    In this post we cover creating Java Threads using the two mechanisms provided in Java, that is, by extending the Thread class and by implementing Runnable interface for concurrent programming.
  • Java Thread Priority Example
    In this post we cover Thread priorities in Java. By default, a java thread inherits the priority (implicit) of its parent thread. Using the setPriority() method you can increase or decrease the thread priority of any java thread.
  • Java ThreadGroup Example
    Sometimes we will need to organize and group our threads into logical groupings to aid in thread management. By placing threads in a threadGroup all threads in that group can be assigned properties as a set, instead of going through the tedious task of assigning properties individually.
  • Java Thread Sleep Example
    We seem to use this method very often to temporarily suspend the current threads execution for a specific period of time. Let's spend some time and familiarize ourselves with what this method actually does.
  • Java Thread Join Example
    In Java, using Thread.join() causes the current thread to wait until the specified thread dies. Using this method allows us to impose an order such that we can make one thread wait until the other completes doing what it needed to do, such as completing a calculation.
  • Examining Volatile Keyword with Java Threads
    When we declare a field as volatile, the JVM will guarantee visibility, atomicity and ordering of the variable. Without it the data may be cached locally in CPU cache and as a result changes to the variable by another thread may not be seen by all other threads resulting in inconsistent behaviour.
  • Java Threads Wait, Notify and NotifyAll Example
    The purpose of using notify() and notifyAll() is to enable threads to communicate with one another via some object on which to performing the locking. A thread using the wait() method must own a lock on the object. Once wait() is called, the thread releases the lock, and waits for another thread to either call notify() or notifyAll() method.
  • Java Thread Deadlock Example and Thread Dump Analysis using VisualVM
    Deadlock is a condition where several threads are blocking forever, waiting for the other to finish but they never do. This tutorial will discuss situations that will lead to Java Thread deadlock conditions and how they can be avoided. In addition, we will discuss using Java VisualVM to pinpoint and analyze the source of the deadlock conditions.
  • Java Thread Starvation and Livelock with Examples
    Starvation occurs when a thread is continually denied access to resources and as a result it is unable to make progress. Thread liveLock is a condition that closely resembles deadlock in that several processes are blocking each other. But with livelock, a thread is unable to make any progress because every time it tries the operation always fails.
  • Java Synchronization and Thread Safety Tutorial with Examples
    One of Java's many strengths come from the fact that it supports multithreading by default as has so from the very onset. One of the mechanisms that Java uses for this is via synchronization. When we use the synchronized keyword in Java we are trying limit the number of threads that can simultaneously access and modify a shared resource. The mechanism that is used in Java's synchronization is called a monitor.
  • Creating a Thread Safe Singleton Class with Examples
    In this tutorial we cover many examples of creating thread-safe singleton classes and discuss some of the shortfalls of each and provide some recommendations on best approaches for a fast, efficient and highly concurrent solution.
  • Java Threads and Concurrent Locks with Examples
    In this tutorial we will focus primarily on using the concurrent utilities and how these can make concurrent programming easier for us.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *