20

Maybe this question has been asked many times before, but I never found a satisfying answer.

The problem:


I have to simulate a process scheduler, using the round robin strategy. I'm using threads to simulate processes and multiprogramming; everything works fine with the JVM managing the threads. But the thing is that now I want to have control of all the threads so that I can run each thread alone by a certain quantum (or time), just like real OS processes schedulers.

What I'm thinking to do:

I want have a list of all threads, as I iterate the list I want to execute each thread for their corresponding quantum, but as soon the time's up I want to pause that thread indefinitely until all threads in the list are executed and then when I reach the same thread again resume it and so on.

The question:

So is their a way, without using deprecated methods stop(), suspend(), or resume(), to have this control over threads?

meteorfox
  • 575
  • 1
  • 5
  • 13
  • 3
    +1 for the nice look of the question! – Martijn Courteaux Apr 12 '10 at 14:40
  • If all you want you want is to a *simulation*, isn't there a much simpler way to do it using latches instead of "going dirty" with wait/notify? I mean, low-level sounds "smart" but really ain't... (just *looking* at the error-prone and unreadable code of Roman's accepted answer I want to puke ;) – SyntaxT3rr0r Apr 12 '10 at 15:17
  • Really nice comment mister wizard , belive me I did my homework on using latches. Maybe you can also post your answer if you are so smart istead of obusing others. Many people would not even understand the answer down there since there are absolutely not familiar with wait/notify so this answer is for them. I posted it for learning a little bit the core concepts of java threading. – Roman Apr 12 '10 at 15:25

3 Answers3

9

Yes, there is:

Object.wait( ), Object.notify() and a bunch of other much nicer synchronization primitives in java.util.concurrent.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
  • More information on this approach can be had here: http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html – James P. Apr 12 '10 at 14:43
6

Who said Java is not low level enough?

Here is my 3 minute solution. I hope it fits your needs.

import java.util.ArrayList;
import java.util.List;

public class ThreadScheduler {

    private List<RoundRobinProcess> threadList
            = new ArrayList<RoundRobinProcess>();

    public ThreadScheduler(){
        for (int i = 0 ; i < 100 ; i++){
            threadList.add(new RoundRobinProcess());
            new Thread(threadList.get(i)).start();
        }
    }


    private class RoundRobinProcess implements Runnable{

        private final Object lock = new Object();
        private volatile boolean suspend = false , stopped = false;

        @Override
        public void run() {
            while(!stopped){
                while (!suspend){
                    // do work
                }
                synchronized (lock){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
        }

        public void suspend(){
            suspend = true;
        }
        public void stop(){
            suspend = true;stopped = true;
            synchronized (lock){
                lock.notifyAll();
            }
        }

        public void resume(){
            suspend = false;
            synchronized (lock){
                lock.notifyAll();
            }
        }

    }
}

Please note that "do work" should not be blocking.

Alex
  • 8,093
  • 6
  • 49
  • 79
Roman
  • 7,933
  • 17
  • 56
  • 72
  • Nice, but as you said yourself, "do work" should not be blocking, so this only works with limited use cases. – fish Apr 12 '10 at 14:56
  • Well ,the limitation could easily be removed by interrupting / or notifying the specific blocking operation. It really dependenc on the "do work". This is generic solution. There are also certain IO blocking operations that cant be interrupted at all. – Roman Apr 12 '10 at 15:00
  • Thanks for the fast answer, I'll see what I can do with this. – meteorfox Apr 12 '10 at 15:02
  • In my case, "do work" is not blocking it just executes a bunch of stuff. So no worries there. Again thanks! – meteorfox Apr 12 '10 at 15:22
0

Short answer: no. You don't get to implement a thread scheduler in Java, as it doesn't operate at a low enough level.

If you really do intend to implement a process scheduler, I would expect you to need to hook into the underlying operating system calls, and as such I doubt this will ever be a good idea (if remotely possible) in Java. At the very least, you wouldn't be able to use java.lang.Thread to represent the running threads so it may as well all be done in a lower-level language like C.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • 2
    It is normally up to the operating system, so you can't even do it from C in an application (unless you go for the likes of the old "green" threads). As it happens, most operating systems are implemented in C or C++. – Tom Hawtin - tackline Apr 12 '10 at 14:42
  • Well I disaggree , you just misunderstood the question I guess. He does not really wants to create a operation system. Just a thread pool that give the option to suspend and resume threads. No connection to any C or low level or anthing else. – Roman Apr 12 '10 at 14:52
  • Yes, that's exactly what I meant. But I understand your argument Andrzej, with Java you feel that you're on a bubble, where JVM does everything for you. Sometimes it's nice to have that, but sometimes you want to have control. – meteorfox Apr 12 '10 at 15:01