Java Thread Priority Not Affected

This is a thread priority test. Code is from thinking in Java p.809

import java.util.concurrent.*; public class SimplePriorities implements Runnable { private int countDown = 5; private volatile double d; // No optimization private int priority; public SimplePriorities(int priority) { this.priority = priority; } public String toString() { return Thread.currentThread() + ": " + countDown; } public void run() { Thread.currentThread().setPriority(priority); while (true) { // An expensive, interruptable operation: for (int i = 1; i < 10000000; i++) { d += (Math.PI + Math.E) / (double) i; if (i % 1000 == 0) Thread.yield(); } System.out.println(this); if (--countDown == 0) return; } } public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) exec.execute(new SimplePriorities(Thread.MIN_PRIORITY)); exec.execute(new SimplePriorities(Thread.MAX_PRIORITY)); exec.shutdown(); } } 

I wonder why I cannot get a regular result, for example:

 Thread[pool-1-thread-6,10,main]: 5 Thread[pool-1-thread-6,10,main]: 4 Thread[pool-1-thread-6,10,main]: 3 Thread[pool-1-thread-6,10,main]: 2 Thread[pool-1-thread-6,10,main]: 1 Thread[pool-1-thread-3,1,main]: 5 Thread[pool-1-thread-2,1,main]: 5 Thread[pool-1-thread-1,1,main]: 5 Thread[pool-1-thread-5,1,main]: 5 Thread[pool-1-thread-4,1,main]: 5 ... 

but random result (every time I run it):

 Thread[pool-1-thread-2,1,main]: 5 Thread[pool-1-thread-3,1,main]: 5 Thread[pool-1-thread-4,1,main]: 5 Thread[pool-1-thread-2,1,main]: 4 Thread[pool-1-thread-3,1,main]: 4 Thread[pool-1-thread-1,1,main]: 5 Thread[pool-1-thread-6,10,main]: 5 Thread[pool-1-thread-5,1,main]: 5 ... 

I am using the i3-2350M 2C4T CPU with Win 7 64-bit JDK 7. Does it matter?

+9
java multithreading windows java-7
source share
11 answers

Java thread priority has no effect

Thread priorities work on most operating systems, but often have minimal effect. Priorities help streamline threads that are only in the execution queue, and do not change the frequency of threads in any main mayer, unless you use a ton of CPU in each thread.

Your program uses a lot of CPU resources, but if you have fewer cores than threads, you may not see any changes in the output order by prioritizing the threads. If there is a free processor, then it is planned to start even a thread with a lower priority.

In addition, topics never starved. Even a thread with a lower priority will start quite often in a situation like this. You should see that threads with a higher priority need to be allocated time for more frequent work, but this does not mean that threads with a lower priority will wait for the completion of their operations before starting themselves.

Even if priorities help allocate more CPU to one thread than others, multi-threaded programs are subject to race conditions that help introduce a large number of chances into their execution. However, you should see that the thread with the highest priority is more likely to spit out its message 0 more often than the others. If you add priority to println() , this will become apparent after a few starts.

It is also important to note that System.out.println(...) is a synchronized method that writes I / O, which will significantly affect the interaction of threads, and different threads block each other. In addition, Thread.yield(); may not be available depending on how the OS schedules threads.

but the random result (every time I run it changes):

Correctly. The output from a multi-threaded program is rarely, if ever, “perfect,” because by definition, threads work asynchronously. We want the output to be random, because we want the threads to work in parallel independently of each other. This is their strength. If you expect some kind of accurate output, then you should not use streams.

+15
source share

The priority of the threads is implementation dependent. In particular, in Windows:

Thread priority is not very significant when all threads compete for the processor. ( Source )

The book "Java Concurrency in Practice" also says

Avoid the temptation to use thread priorities as they increase platform dependency and can cause viability issues. Most concurrent applications can use the default priority for all threads.

+12
source share

Thread priority does not guarantee execution order. It comes into play when resources are limited. If the system works with restrictions due to memory or processor, then threads with higher priority will be executed first. Assuming you have enough system resources (which I would suggest for a simple program and the system resources you published), then you will not have any system restrictions. Here is a blog post (not my post). I found that it provides additional information about this: Why thread priority rarely matters .

+9
source share

Let it simplify and go straight to the source ...

Each thread has priority. When there is competition for processing resources, higher priority threads tend to be preferred to lower priority threads. There are no such preferences, however, there is a guarantee that the thread with the highest priority will always be , and the thread priorities cannot be used for reliable implementation of mutual exclusion.

  • from the Java Language Specification (2nd Edition) p. 445.

Also...

Although thread priorities exist in Java, and many links claim that the JVM will always choose one of the threads with the highest priority for planning [52, 56, 89], this is not currently guaranteed by the Java Language or Virtual Machine Specification [53, 90]. Priorities are only hints for the planner [127, p. 227].

  • from testing parallel Java components (PhD Thesis, 2005) p. 62.

  • Ref. 127, p. 227 (from the above excerpt) is component software: in addition to object-oriented programming (C. Szyperski), Addison Wesley, 1998.

In short, do not rely on thread priorities .

+7
source share

Thread priority is just a hint at the OS task scheduler. The task scheduler will try to allocate more resources to the higher priority thread, however there are no explicit guarantees.

In fact, this applies not only to Java or the JVM. Most real-time operating systems use thread priorities (managed or unmanaged) only in a suggestive way.

Jeff Atwood has a good post on "Priority Topics is Evil"

Here is the problem. If someone starts the work that will make "cond" true in the downstream (producer), and then the time the program is such that the higher priority thread that this spinning (consumer) gives out is planned, the consumer will starve the manufacturer completely. This is a classic race. And although there is a clear dream there, betraying it does not allow the manufacturer to be planned, because it has a lower priority. The consumer simply spins forever, and if the free processor does not open, the producer will never produce. Unfortunately,

+5
source share

As mentioned in other answers, the priority of a thread is more a hint than a definition of a strict rule.

However, if priority is considered strictly (er), your test setup will not produce the result that you call "expected". First you create 5 threads with the same low priority and one thread with high priority.

  • The processor you are using (i3) has 4 threads of its own. Thus, even if a high priority means that the thread is running without interruption (which is wrong), low priority threads will receive 3/4 of the processor power (if there is no other task). This processor power is distributed over 5 threads, so low priority threads will run at a speed of 4 * 3/4 ​​* 1/5 = 3/5 times faster than a high priority thread. After the high priority stream is completed, the low priority streams operate at 4/5 of the high priority stream speed.

  • You start low priority threads before high priority threads. Therefore, they begin a little earlier. I expect that in most systems, "priority" is not implemented until the nanosecond. Thus, the OS will allow threads to run “a little longer” until they switch to another thread (to reduce the impact of the switching cost). Therefore, the result greatly depends on how this switch is implemented and how large the task is. If the task is small, it is possible that the switch will not happen, and in your example all low-priority threads will be executed first.

  • These calculations suggested that high and low priority are interpreted as extreme cases. In fact, the priority is something like “in n out of m cases prefers this” with the variable n and m.

  • You have Thread.yield in your code! This will pass execution to another thread. If you do this too often, this will cause all threads to get equal CPU power.

Therefore, I would not expect the conclusion that you spoke about in your question, namely, that the high priority thread ends first, and then the low priority downstream thread ends.

In fact: with the Thread.yield line, I get the result that each thread receives the same processor time. Without the Thread.yield line and increasing the number of calculations by 10 times and increasing the number of threads with low priority by 10 times, I get the expected result, namely, that the high priority thread ends earlier with some factor (which depends on the number of built-in processor threads).

+3
source share

I believe that the OS is free to ignore Java thread priority.

+1
source share

Thread priority is a hint (which can be ignored), so when you have a 100% processor, the OS knows that you want to prefer some threads over others. The priority of the stream must be set before the start of the stream or it can be ignored.

On Windows, you must be an administrator in order to prioritize a thread.

+1
source share

A few things to consider:

+1
source share

Some operating systems do not provide proper thread priority support.

0
source share

You should understand that different OSs work differently with thread priorities. For example, Windows uses a pre-emptive scheduler, which gives a longer time span to higher priority threads, while some other (very old) operating systems use a non-priority scheduler where a higher priority thread runs completely ahead of a higher priority thread low priority if a thread with a higher priority does not go into sleep mode or does not perform some I / O operations, etc.

That's why it is not guaranteed that a thread with a higher priority runs completely, it actually runs longer than threads with a low priority, so your outputs are ordered in this way.

To find out how Windows handles multithreading, follow the link below:

https://docs.microsoft.com/en-us/windows/win32/procthread/multitasking

0
source share

All Articles