0
votes

I am curious how to implement a FIFO (first in, first out) algorithm in Java. I have 3 classes already created, but have to implement the scheduling algorithms for FIFO and SJF (Shortest Job First).

For the simulator class, we have the following variables:

private CPU cpu1;
private ArrayList<Process> ready;
private ArrayList<Process> finished;
private int time;

Then the method is:

public Process select(ArrayList<Process> ready){
    if(SCHEDULING_ALGORITHM.equals("FIFO"))
    {
        //add code here
    }
    else if(SCHEDULING_ALGORITHM.equals("SJF"))
        //add code here
    }

other methods are:

public void addProcess(String name, int start, int length)
{
    Process temp = new Process(name, start, length);
    ready.add(temp);
}

There are two other classes Process and CPU. Process holds any information about a single process that should be stored there.

1

1 Answers

0
votes

FIFO is the exact structure of a Queue. You can use Java's ArrayDeque implementation to create a Queue for a FIFO implementation. Use the poll() method on the ArrayDeque to get the next object out of the Queue.

ArrayDeque<Object-Type-Here> queue = new ArrayDeque<>();
//add your objects to the queue here in a first-in-first-out manner
------------------------------
//Here's how to get the first thing out of the queue
queue.poll();

For SJF, you can use a min-heap. For this, use Java's PriorityQueue implementation. You might need to implement Comparable or create a compareTo function depending on how you want to implement the solution. The compareTo function will allow the priorityQueue to automatically sort like a min-heap does. Use the poll() method for this as well.

PriorityQueue<Object-Type-Here> pq = new PriorityQueue<>();
//add your objects to the min-heap here for a shortest-job-first implementation