Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multithreading - thread priority

Can anybody explain how thread priority works in java. The confusion here is if java does'nt guarantee the implementation of the Thread according to its priority then why is this setpriority() function used for.

My code is as follows :

public class ThreadSynchronization implements Runnable{

    public synchronized void run() {
        System.out.println("Starting Implementation of Thread "+Thread.currentThread().getName());
        for(int i=0;i<10;i++)
        {
            System.out.println("Thread "+Thread.currentThread().getName()+" value : "+i);
        }
        System.out.println("Ending Implementation of Thread "+Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        System.out.println("Program starts...");
        ThreadSynchronization th1 = new ThreadSynchronization();
        Thread t1 = new Thread(th1);
        t1.setPriority(1);
        synchronized(t1)
        {
            t1.start();
        }

        ThreadSynchronization th2 = new ThreadSynchronization();
        Thread t2 = new Thread(th2);
        t2.setPriority(9);
        synchronized (t2) {
            t2.start(); 
        }

        System.out.println("Program ends...");
    }
}

In the above program even if I change the priority I find no difference in the output. Also a real time application of how thread priority can be used would be of great help. Thanks.

like image 812
Neal Avatar asked Dec 02 '13 16:12

Neal


People also ask

Which thread has highest priority in Java?

All Java threads have a priority, and the JVM serves the one with the highest priority first. When we create a Thread, it inherits its default priority. When multiple threads are ready to execute, the JVM selects and executes the Runnable thread that has the highest priority.

How do you prioritize a thread in Java?

It can be changed using the method setPriority() of class Thread. There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY. The values of these variables are 1, 10 and 5 respectively.

What is normal thread priority in Java?

The default priority of a Java thread is NORM_PRIORITY . (A Java thread that doesn't explicitly call setPriority runs at NORM_PRIORITY .) A JVM is free to implement priorities in any way it chooses, including ignoring the value.

What is different thread priority?

Thread priority in Java is a number assigned to a thread that is used by Thread scheduler to decide which thread should be allowed to execute. In Java, each thread is assigned a different priority that will decide the order (preference) in which it is scheduled for running.


4 Answers

Thread priority is just a hint to OS task scheduler and is dependent on the underlying OS. OS will try to allocate more resources to a high priority thread but it does not guarantee it. So if your program is dependent on thread priorities than you are in-turn binding your program to underlying OS, which is bad.

From Java Concurrency in Practice:

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.

like image 193
Trying Avatar answered Oct 05 '22 12:10

Trying


Thread priority is only a hint to OS task scheduler. Task scheduler will only try to allocate more resources to a thread with higher priority, however there are no explicit guarantees.

In fact, it is not only relevant to Java or JVM. Most non-real time OS use thread priorities (managed or unmanaged) only in a suggestive manner.

Also very important, Priorties are different to every underlying plattform. Therefore you kind of loose your plattform freedom of java. See this summary as well:

Indeed, some priority levels can map to the same "native" priority level. Here's the list (based on the Hotspot code in OpenJDK 6):

Solaris
1 ⇒ 0
2 ⇒ 32
3 ⇒ 64
4 ⇒ 96
5 – 10 ⇒ 127
Of note is that on Solaris, you can't raise the thread priority above normal, only lower it: the priority value for 5 is the same as any of the higher values.

Linux
1 – 10 ⇒ 4 – -5 (nice values) Of note is that on Linux, different thread priorities in Java do map to distinct priority values at native level.

Windows
1 – 2 ⇒ THREAD_PRIORITY_LOWEST
3 – 4 ⇒ THREAD_PRIORITY_BELOW_NORMAL
5 – 6 ⇒ THREAD_PRIORITY_NORMAL
7 – 8 ⇒ THREAD_PRIORITY_ABOVE_NORMAL
9 – 10 ⇒ THREAD_PRIORITY_HIGHEST

I've developed a lot of multi threaded java applications, and in my opinion if you have to set thead priorities you have another problem. Like a bad algorythm that consumes to much cpu time etc.... I always suggest to not change the java thread prio, since you can't rely on it anyways. (of course there are some scenarios where it makes sense)

like image 27
Colin Avatar answered Oct 05 '22 13:10

Colin


There are several situations where setting a priority for a Thread is useful, you just must not start believing in any guarantees that come form such settings, as always: the order of execution with threads is undefined. If you think that your thread will be done earlier if you give it a higher priority, please read the statement above again until that's out of your head. ;)

You should define the priority based on how important it is for this thread to gain execution time compared to the others. Even though the underlaying system guarantees nothing, it still can provide a benefit for those JVMs that support it.

Example: You have a program that does some heavy calculation based on user input in your JFrame. It is a good practice to set those background threads to a low priority, because it is more important that the JFrame is responsive than working on the calculation (which will take a long time to finish anyways, a few more millis won't hurt). The OS will still assign most CPU time to the low priority threads, unless something more important needs it. But then it is good that this more important stuff gets the priority.

Now it could happen that on some systems the priority setting is ignored and the JFrame is again unresponsive, but then this does nothing worse to your code then not setting the priority to low in the first place.

like image 39
TwoThe Avatar answered Oct 05 '22 13:10

TwoThe


The size of the tasks is too small and probably will complete right after the start. Also, if you have "enough" CPU cores, each worker thread will be allocated to one core, so the result will be the same.

Try the experiment in a different context, first increase the task size (for example by looping one thousand times to one million, without print) then increase the number of threads to exceed the number of cores you have and third, create your threads first and then start all the threads (you cannot start them at once, you will still need to loop through them).

In my case, I have chosen 10 threads because I ran the code on a processor with two hyper-threaded cores, running four simultaneous threads.

My changes to your example:

public class ThreadPriority implements Runnable {

    public synchronized void run() {
        System.out.println("Starting Implementation of Thread " + Thread.currentThread().getName());
        float s = 0;
        for (int i = 0; i < 1000; i++)
            for (int k = 0; k < 1000000; k++)
                s += k;
        System.out.println("Ending Implementation of Thread " + Thread.currentThread().getName() + " " + s);
    }

    Thread t;

    public ThreadPriority(String name, int prio) {
        t = new Thread(this);
        t.setName(name);
        t.setPriority(prio);
    }

    public void start() {
        synchronized (t) {
            t.start();
        }
    }

    public static void main(String[] args) {
        System.out.println("Program starts...");
        ThreadPriority[] th = new ThreadPriority[10];
        for (int i = 0; i < th.length; i++) {
            th[i] = new ThreadPriority("T" + i, i / 2 + 1);
        }

        for (ThreadPriority tp : th)
            tp.start();

        System.out.println("Program ending, wait for all the threads to complete");
    }
}

Results are:

Program starts...
Starting Implementation of Thread T0
Starting Implementation of Thread T9
Starting Implementation of Thread T8
Starting Implementation of Thread T5
Program ending, wait for all the threads to complete
Starting Implementation of Thread T4
Starting Implementation of Thread T6
Starting Implementation of Thread T7
Starting Implementation of Thread T2
Starting Implementation of Thread T3
Starting Implementation of Thread T1
Ending Implementation of Thread T6 1.7592186E13
Ending Implementation of Thread T7 1.7592186E13
Ending Implementation of Thread T4 1.7592186E13
Ending Implementation of Thread T8 1.7592186E13
Ending Implementation of Thread T9 1.7592186E13
Ending Implementation of Thread T5 1.7592186E13
Ending Implementation of Thread T2 1.7592186E13
Ending Implementation of Thread T0 1.7592186E13
Ending Implementation of Thread T1 1.7592186E13
Ending Implementation of Thread T3 1.7592186E13

As you can see, the low number threads tend to end later, because the high number threads have higher priority. By turning the scale upside down:

    for (int i = 0; i < th.length; i++) {
        th[i] = new ThreadPriority("T" + i, 9 - i / 2 );
    }

The low number threads complete faster than the high ones. Some threads complete even before other threads are started, because they have higher priority compared to the calling program:

Program starts...
Starting Implementation of Thread T0
Starting Implementation of Thread T1
Starting Implementation of Thread T2
Starting Implementation of Thread T3
Program ending, wait for all the threads to complete
Ending Implementation of Thread T2 1.7592186E13
Ending Implementation of Thread T3 1.7592186E13
Ending Implementation of Thread T0 1.7592186E13
Ending Implementation of Thread T1 1.7592186E13
Starting Implementation of Thread T9
Starting Implementation of Thread T4
Starting Implementation of Thread T8
Starting Implementation of Thread T7
Starting Implementation of Thread T5
Starting Implementation of Thread T6
Ending Implementation of Thread T4 1.7592186E13
Ending Implementation of Thread T5 1.7592186E13
Ending Implementation of Thread T7 1.7592186E13
Ending Implementation of Thread T8 1.7592186E13
Ending Implementation of Thread T9 1.7592186E13
Ending Implementation of Thread T6 1.7592186E13
like image 25
Razvan Popovici Avatar answered Oct 05 '22 13:10

Razvan Popovici