Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java preemptive?

I've seen many answers to this question but I'm still not sure.

One of them was "Java is preemptive". (The JVM schedules using a preemptive, priority based scheduling algorithm (usually round robin algorithm).

The second was that if 2 threads with the same priority run Java will not preempt and one thread could starve.

So now I wrote a program to check it out, I created 10 threads with minimum priority followed by 10 threads with maximum priority, the results were that I jump between all of the threads - meaning Java is preemptive even if 2 threads are with the same priority

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @
 */
public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        for (int i=0;i<10;i++){
            Thread t=new Thread(new Dog(i));
            t.setPriority(Thread.MIN_PRIORITY);
            t.start();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
        }
        for (int i = 0; i < 10; i++) {
            Thread g = new Thread(new Dog(i+10));
            g.setPriority(Thread.MAX_PRIORITY);
            g.start();
        }

    }
}

t

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author Matan2t
 */
public class Dog implements Runnable{
    public int _x=-1;
    public Dog(int x){
        _x=x;
    }
    @Override
    public void run(){
        while(true){
            System.out.println("My Priority Is : " + _x);
        }
    }

}
like image 380
Matan Touti Avatar asked Jan 27 '13 08:01

Matan Touti


Video Answer


1 Answers

I don't believe this is specified as precisely as either of the two quotes would suggest. All I could find was:

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread.

Beyond that, I believe the mechanics are platform- and JVM-specific. On the platforms that I am familiar with, the JVM uses OS threads and thus relies on the OS scheduler.

That said, given that all application threads by default have the same priority, it would be incredibly inconvenient if those threads were not capable of preempting one another.

like image 158
NPE Avatar answered Sep 20 '22 18:09

NPE