`

Java thread priority

    博客分类:
  • JAVA
 
阅读更多

比较好的java书上都写着不要试图用java线程的优先级来确定线程的执行顺序,不过知道下java线程优先级与底层OS之间线程优先级的映射关系也是好的,找了篇文章总结的不错。

转载自:http://www.javamex.com/tutorials/threads/priority_what.shtml

 

What is Java thread priority?

In our introduction to thread priority, we pointed out some problems with the system, notably differences between what priority actually means on different systems. Here, we'll look at how thread priority is actually implemented in Windows and Linux.

Windows priorities

In the Hotspot VM for Windows, setPriority() map to Windows relative priorities (set by the SetThreadPriority() API call). The actual mappings were changed between Java 5 and Java 6 as follows:

Java to Windows priority mappings

 

Java Priority Windows Priority (Java 5) Windows Priority (Java 6)
1 THREAD_PRIORITY_LOWEST
2
3 THREAD_PRIORITY_BELOW_NORMAL
4
5 THREAD_PRIORITY_NORMAL THREAD_PRIORITY_NORMAL
6 THREAD_PRIORITY_ABOVE_NORMAL
7 THREAD_PRIORITY_ABOVE_NORMAL
8 THREAD_PRIORITY_HIGHEST
9 THREAD_PRIORITY_HIGHEST



CPU allocation against thread priority

Figure 1. Approximate CPU allocation against thread priority under Windows XP on a uniprocessor machine. Results for Vista on a dual core machine are very similar.

CPU allocation against thread priority (Linux)

Figure 2. Approximate CPU allocation against thread priority on a uniprocessor machine under Debian Linux (kernel 2.6.18).

In effect, the priority mappings were 'shifted down' to avoid THREAD_PRIORITY_TIME_CRITICAL, apparently following reports that this setting could affect vital processes such as audio. Note that there is really no such mapping to THREAD_PRIORITY_IDLE as suggested by Oaks & Wong (they were possibly misinterpreting a dummy value that appears at the beginning of the priority mapping table in the VM source code).

On Windows, thread priority is a key element in deciding which thread gets scheduled, although the overall priority of a thread is a combination of the process's priority class, the thread's relative priority (values from the table above), plus any temporary "boost" given in specific circumstances (such as on returning from a wait on I/O). But in general:

Lower-priority threads are given CPU when all higher priority threads are waiting (or otherwise unable to run) at that given moment.

The actual proprtion of CPU allotted to a thread therefore depends on how often that situation occurs— there's no relation per se between priority and CPU allocation. Now of course, if this was literally the be-all and end-all to thread scheduling, then there'd quite possibly be lower-priority threads that barely got any CPU at all, being continually starved by higher-priority threads that needed CPU. So Windows has a fallback mechanism, whereby a thread that hasn't run for a long time is given a temporary priority boost. (For more details about some of the points mentioned here, see the section on thread scheduling.)

What this generally means is that on Windows:

Thread priority isn't very meaningful when all threads are competing for CPU.

As an illustration, Figure 1 opposite shows the results of an experiment in which ten threads are run concurrently, one thread with each Java priority. Each thread sits in a CPU-intensive loop (continually a random number using a XORShift generator). Each thread keeps a count of how many numbers it has generated1. After a certain period (60 seconds in this case), all threads are told to stop and queried to find out how many numbers they generated; the number generated is taken as an indication of the CPU time allocated to that thread2. As can be seen, thread priorities 1-8 end up with a practically equal share of the CPU, whilst priorities 9 and 10 get a vastly greater share (though with essentially no difference between 9 and 10). The version tested was Java 6 Update 10. For what it's worth, I repeated the experiment on a dual core machine running Vista, and the shape of the resulting graph is the same. My best guess for the special behaviour of priorities 9 and 10 is that THREAD_PRIORITY_HIGHEST in a foreground window has just enough priority for certain other special treatment by the scheduler to kick in (for example, threads of internal priority 14 and above have their full quantum replenished after a wait, whereas lower priorities have them reduced by 1).

Java thread priority to nice value mappings in Linux Java thread priority Linux nice value
1 4
2 3
3 2
4 1
5 0
6 -1
7 -2
8 -3
9 -4
10 -5

Linux priorities

Under Linux, you have to go through more hoops to get thread priorities to function at all, although in the end, they may be more useful than under Windows. In Linux:

  • thread priorities only work as of Java 6 onwards;
  • for them to work, you must be running as root (or with root privileges via setuid);
  • the JVM parameter -XX:UseThreadPriorities must be included.

The rationale behind requiring root privileges to alter thread priorities largely eludes me. Whether or not Linux itself generally should place such a restriction on changing nice values is arguable, bit since it doesn't, it seems odd to add it to the JVM (as opposed to, say, building in a restriction via the Java SecurityManager). And does anyone really run, say, their web server as root?

Assuming you go through these steps to enable them, Java thread priorities in Hotspot map to nice values. Unlike Windows priorities, Linux nice values are used as a target for CPU allocation (although like Windows, recent versions of Linux— from kernel 2.6.8 onwards— also apply various heuristics to temporarily boost or penalise threads). The mappings from Java priorities to Linux nicevalues are given in the table opposite. Note that:

  • nice value means "how nice the thread is to other threads", so a lower number means higher priority;
  • Java doesn't actually map to the full range (nice values go from -20 to 19), probably to prevent negative impact on system threads.

Figure 2 shows the results of the thread priority experiment repeated under Linux with kernel 2.6.18. The different coloured traces simply represent 3 separate runs of the experiment. The graph shows that there is a correlation between Java priority (nice value) and CPU allocation, although it is far from linear.

Solaris priorities

Sun have published more detailed information on Solaris thread priorities.


1. To reduce the number of memory writes, each thread actually incremented the counter when the bottom 7 bits of the random number generated were all set. However, this should not affect the test, since millions of numbers were generated by each thread, and the bits of numbers generated by XORShift are generally considered equally random.
2. For validation purposes, each thread also recorded its elapsed CPU time as reported by ThreadMXBean. The corresponding graphs have essentially the same shape, but on the machines tested on, the granularity of measurements using the count method is actually better.

分享到:
评论

相关推荐

    Java_programming_code_improve_thread_priority.rar_java programmi

    Java编程实现提高线程优先级经典代码Java programming code to improve thread priority Classic

    ThreadPriority.java

    class ThreadDemo extends Thread { public thread1(String s) { super(s);... thread1.setPriority(thread.MIN_PRIORITY); thread1.setPriority(thread.MIN_PRIORITY); thread1.start(); thread2.start(); } }

    java 线程Sample

    ExecutorService exec=Executors.newFixedThreadPool(2); Thread1 th1 = new Thread1("CRTA"); th1.setDaemon(true);... th1.setPriority(MIN_PRIORITY); th1.start(); Thread1 th2 = new Thread1("CRTB");

    JAVA多线程编程详解-详细操作例子

    本压缩包,总共包含两个文档,JAVA多线程编程详解-详细操作例子和 Java... 例如,runnable、thread、stop()、 suspend、yield、setPriority()、getPriority()、synchronized、wait()、join、线程池同步阻塞等方法的介绍

    thread_priority_setting_on_android

    thread_priority_setting_on_android 研究android上两种线程优先级设置方法:Thread.setPriority()、android.os.Process.setThreadPriority()。 很明显,后者对优先级的控制更有效,因为具有最高优先级的线程的...

    Java测试题1答案

    2) Another thread is given a higher priority 3) A call to the thread’s stop method 4)A call to the halt method of the Thread class 21、在Servlet生命周期中的哪些方法只被执行一次 1)...

    Java多线程的调度_动力节点Java学院整理

     java.lang.Thread 提供了 setPriority(int newPriority) 方法来设置线程的优先级,但线程的优先级是无法保障线程的执行次序的,优先级只是提高了优先级高的线程获取 CPU 资源的概率。也就是说,这个方法不靠谱。

    整理后java开发全套达内学习笔记(含练习)

    Thread [java] 线程 [θred] throw (关键字) throws (关键字) [θrәu] 抛出(异常) transient (关键字) 瞬变;临时的['trænziәnt]'(可序列化) valid 正确的,有效的 ['vælid] variable n.变量 a.可变的['vєә...

    验证后台线程的java多线程技术

    这个程序验证了后台线程与用户线程的区别以及之间的关系,证明了只要所有的用户线程结束了,那么后台线程将必须结束! import java.util....  Thread.currentThread().setPriority(Thread.MIN_PRIORITY);  Thr

    Group6_Thread_safe_PriorityQueues:LockFreeQueue和PipelinedBlockingQueue的实现

    线程安全PriorityQueues #操作说明实现在并发访问下性能比Java的PriorityBlockingQueue更好的pipelinedPriorityQueue和lockfreePriorityQueue。 #要求Java 1.8+ Eclipse中的Maven插件蚀#如何使用用Eclipse打开...

    threadly:一个工具库,用于协助安全的并发Java开发。 提供独特的基于优先级的线程池,以及安全分配线程工作的方式

    螺纹地 Java工具库,用于协助并发Java应用程序的开发。 它包括一系列工具,可满足广泛的并发开发和测试需求。 它被设计为对java.util.concurrent的补充,并使用java.util.concurrent... PriorityScheduler与java.util.

    Java期末复习||应用程序设计-多线程和泛型

    Java应用程序设计之多线程和泛型 Thread、Runnable、Callable 线程操作:isAlive()、isInterrupted()、join()、sleep()、stop()、interrupted()、setDaemon()、setPriority()、yield() 同步与死锁、Object类对线程的...

    Thinking in Java 4th Edition

    Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4th edition........................ 2 Changes .......................................... 3 Note on the ...

    Android线程的优先级设置方法技巧

    Android在线程方面主要使用的是Java本身的Thread类,我们可以在Thread或Runnable接口中的run方法首句加入Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //设置线程优先级为后台,这样当多个线程...

    j2se项目源码及介绍_飞鸽传书

    public void setPriority(String priority) public String getUserName() public void setUserName(String userName) public static User getSelf() 获取本机的User对象。 public String toString() ...

    log4j日志驱动包

    [start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n #应用于文件 log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=file.log log4j.appender....

    AdvancedAsyncTask:增强的Android AsyncTask库

    AdvancedAsyncTask 总览 此库已增强,可以使用AsyncTask api。 产品特点 ... implementation ' net.sjava:advancedasynctask:1.1.0 ' } Maven < groupId>net.sjava</ groupId> < artif

    android logcat使用

    brief process tag thread raw time threadtime long -c 清除所有log并退出 -d 得到所有log并退出 (不阻塞) -g 得到环形缓冲区的大小并退出 -b <buffer> 请求不同的环形缓冲区 ('main' (默认), 'radio', '...

    飞机大战游戏

    gb.Game_star = new Thread(this); gb.y = -(5 * a.y); gb.hero_x = a.x / 2 - 50; gb.hero_y = a.y - 150; gb.hero_oldx = gb.hero_x; gb.hero_oldy = gb.hero_y; gb.hero_hp = -1; gb.seq = 0; ...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...

Global site tag (gtag.js) - Google Analytics