Java Thread Priorities + User or Daemon Threads

Setting Thread Priorities; User and Daemon Threads

Thread priorities

In Java every thread possesses a priority, that helps the thread scheduler to allocate the ressources needed.

As such, the priorities range from 1 (minimum priority) to 10 (maximum priority), with 5 representing the normal priority.

The Thread class defines three constant priority levels:

  • Thread.MIN_PRIORITY = 1
  • Thread.NORM_PRIORITY = 5
  • Thread.MAX_PRIORITY = 10

While you can use these constants, you can also define your own priority level:

Thread t1 = newThread;
t1.setPriority(7);
Thread t2 = newThread;
t2.setPriority(Thread.NORM_PRIORITY);

One word of caution when setting thread priorities though: pay attention when defining high priority threads, since thread starvation (when a thread is unable to gain regular access to shared resources and is therefore unable to make progress) can definitely happen and is best avoided.

Furthermore, thread priorities are often maped to the priorities of the host operation system. Just don't overuse them.

User and Daemon Threads

Another important characteristic of Java threads is that there are two types of threads:

  • User Threads (the normal thread) created by default by the Java Virtual Machine (JVM), and

  • Daemon Threads, that you need to explicitely declare. Daemon threads have lower priorities than user threads and are meant to serve in the background user threads.

//declaring a Thread

Thread daemonThread = new Thread(new Runnable() {
    public void run() {
        // do something
    }
});

 //initializing and starting the Daemon Thread

daemonThread.setDaemon(true);
daemonThread.start();

A thread inherits daemon status from its parent or creator thread. The JVM will exit any running daemon threads once the user threads terminate. Running only daemon threads is therefore not possible.

Hope this helps and keep on learning!