Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule Java Threads

I have read that Java threads are user-level threads and one of the differences between user level threads and kernel level threads is that kernel level threads are scheduled by the kernel(we cannot change it) where as for user level threads we can define our own scheduling algorithm.

So how do we schedule threads in Java? At any given time, when multiple threads are ready to be executed, the runtime system chooses the Runnable thread with the highest priority for execution. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion. What if I don't want RR? is there a way I can change it or am I missing something here?

like image 995
Aniket Thakur Avatar asked Jul 24 '13 07:07

Aniket Thakur


3 Answers

You cannot change the scheduling algorithm as for the JVM this is outside the scope. The JVM uses the threading of user threads provided by the underlying OS.

So from the Java perspective you cannot change the scheduling algorithm. The scheduling is done automatically.

The only thing in Java you can do is set the priority of the thread. But how this affects the scheduling algorithm is not defined.

You can try to change the scheduling algorithm of the OS where your VM is running on. But this is highly dependend on the OS used.

like image 139
Uwe Plonus Avatar answered Oct 03 '22 09:10

Uwe Plonus


For the last 10 years or so JVM threads are system-level threads and not user-level ('green') threads. Even for user-level threads, you don't get to manage them (the JVM does).

like image 30
Tassos Bassoukos Avatar answered Oct 03 '22 08:10

Tassos Bassoukos


The JVM Spec does not state how threads are supposed to be scheduled by an implementation. The Hotspot VM (and most likely almost every other implementation as well) use the OS scheduling mechanisms (as Uwe stated). See also What is the JVM Scheduling algorithm?.

A simple, yet most likely not very efficient way to influence scheduling of your application threads would be to have only n runnable threads for the OS to schedule (n being the number of threads you'd actually like to run in parallel). That could e.g. be your own implementation of ExecutorService, which makes all threads you don't want to be scheduled by the OS wait until you think they should run. Of course this way you don't have any influence on other VM threads, let alone other applications or the OS.

A lot more involved (and not plattform independent) would be to change the OS scheduler itself to something more tailored to the needs of a JVM. A quick google research found this abstract, and I guess there's more work done on that field.

like image 28
JohannesR Avatar answered Oct 03 '22 07:10

JohannesR