Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can scheduler to suspend one thread and execute another thread/work?

Lets we have following code(we will run it on single core CPU):

Runnable runnable1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("runnable_1_1");
        System.out.println("runnable_1_2");
    }
};
Runnable runnable2 = new Runnable() {
    @Override
    public void run() {
        System.out.println("runnable_2_1");
        System.out.println("runnable_2_2");
    }
};
ExecutorService executorService = Executors.newSingleThreadExecutor(); // or Executors.newCachedThreadExecutor();
executorService.execute(runnable1);
executorService.execute(runnable2);
executorService.shutdown();

Is it theoretically possible that one task will be wedged to another and we will see output like this:

runnable_1_1
runnable_2_1
runnable_2_2
runnable_1_2

P.S.

Single thread executor is not mandatory for this example. Mandatory that we have only one CPU core

like image 382
gstackoverflow Avatar asked Sep 06 '25 10:09

gstackoverflow


1 Answers

This cannot be cleanly done on Java level for an arbitrary thread, as there are no non-deprecated methods to suspend it. All valid methods of control include the thread actively yielding.

However operating system itself normally has a scheduler that periodically suspends and resumes all running processes, allowing to have much more of them than the number of CPU cores available. Also, Java virtual machine normally does not run just as a single process (green threads belong to the past), there is one process per thread.

As a result, the operating system may suspend one thread for a short time, allowing to run another thread, or some other process outside Java virtual machine. The general answer is likely yes.

like image 70
Audrius Meškauskas Avatar answered Sep 09 '25 01:09

Audrius Meškauskas