How to change the priority of a running java process?

こ雲淡風輕ζ 提交于 2019-11-28 14:06:05
Duncan McGregor

https://stackoverflow.com/questions/257859 discusses how to change the priority of a thread in Windows. I don't know of any Java API to do this, so you're going to have to fall back on JNI to call into the Windows API. In your shoes I think I'd start with JNA which will let you map the functions easily, or find a ready-written Java wrapper to the API if there is one.

Perhaps you are trying to do something the OS does for you.

In Unix, under load, each process is given a short time slice to do its work. If it uses all its time slice it is assume the process is CPU bound it priority is lowers. If it blocks on IO, it is assumed to be IO bound and its priority is raised (because it didn't use all its time slice)

All this only matters if there isn't enough CPU. If you keep you CPU load below 100% most of the time, every process will get as much CPU as it needs and the priority doesn't make much difference.

(The title does not address windows specifically, but the tags do. However I think it might be relevant to know the differences.)

In general scheduling of threads an processes is a kernel dependent feature, there is hardly a portable way to do this. In fact what priority means varies greatkly. For example on NT a high value of 24 means realtime and a value of 1 means idle. On unix this is the opposite: 1 is fastest and larger values are slower.

Of course Java abstracts this information away using .setPriority with a range of 1 (lowest) to 10 (highest).

Something not pointed out yet, but a pretty big problem on many unixes is: By default a user can not increase the priority of a process (that is reduce the nice value), even if the user itself decreased the priority right before.

In contrast on NT I think you can reraise your priority back to default priority.

Simply put: .setPriority may work on windows, but will most likely not work on unix.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!