Question

In: Computer Science

PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a...

PROGRAMMING LANGUAGE : JAVA

  • Problem specification.

In this assignment, you will create a simulation for a CPU scheduler. The number of CPU’s and the list of processes and their info will be read from a text file. The output, of your simulator will display the execution of the processes on the different available CPU’s. The simulator should also display:

-   The given info of each process

-   CPU utilization

- The average wait time

- Turnaround time for each process

- CPU response time for each process

  • Implementation.

You need to start your demo with a UML diagram.

You need to implement the following algorithms:

  • FCFS (First Come First Served)
  • SJF (Shortest Job
  • SRTF (Shortest Remaining Time First)
  • RR with a user given queue
  • Sample input file (text file contents)

numOfCPUs:      4

// list of processes to be scheduled

// processID       arrivalTime          totalExecTime   IO_RequestAtTime         IO_RequestAtTime ...

p0           0              10           2              5              8

p1           2              3

p2           10           7              1              2              3

- Further Details

The first line indicates how many CPU’s/cores do we have in the system. This sample file indicates that we have 4 CPU’s/cores

Any line that starts with // is a comment

Then we have a list of the processes. The first line:

p0           0              10           2              5              8

means we have process with process ID p0 that arrives at time 0. It needs 10 time on the CPU to finish executing its code. 2 time units after it has started, it asks for I/O. Any I/O request is fulfilled in 2 time units. At time 5 of its execution, p0 asks for I/O again. At time 8 of its execution, it asks for I/O again. There is no limit for how many times a process asks for I/O.

p1 does not ask for any I/O.

p2 arrives at time 10. 1 time unit after it stared execution, it requests I/O.

Solutions

Expert Solution

fcfs:

import java.util.*;

public class FCFS {

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

System.out.println("enter no of process: ");

int n = sc.nextInt();

int pid[] = new int[n];   // process ids

int ar[] = new int[n];     // arrival times

int bt[] = new int[n];     // burst or execution times

int ct[] = new int[n];     // completion times

int ta[] = new int[n];     // turn around times

int wt[] = new int[n];     // waiting times

int temp;

float avgwt=0,avgta=0;

for(int i = 0; i < n; i++)

{

System.out.println("enter process " + (i+1) + " arrival time: ");

ar[i] = sc.nextInt();

System.out.println("enter process " + (i+1) + " brust time: ");

bt[i] = sc.nextInt();

pid[i] = i+1;

}

//sorting according to arrival times

for(int i = 0 ; i <n; i++)

{

for(int  j=0;  j < n-(i+1) ; j++)

{

if( ar[j] > ar[j+1] )

{

temp = ar[j];

ar[j] = ar[j+1];

ar[j+1] = temp;

temp = bt[j];

bt[j] = bt[j+1];

bt[j+1] = temp;

temp = pid[j];

pid[j] = pid[j+1];

pid[j+1] = temp;

}

}

}

// finding completion times

for(int  i = 0 ; i < n; i++)

{

if( i == 0)

{

ct[i] = ar[i] + bt[i];

}

else

{

if( ar[i] > ct[i-1])

{

ct[i] = ar[i] + bt[i];

}

else

ct[i] = ct[i-1] + bt[i];

}

ta[i] = ct[i] - ar[i] ;          // turnaround time= completion time- arrival time

wt[i] = ta[i] - bt[i] ;          // waiting time= turnaround time- burst time

avgwt += wt[i] ;               // total waiting time

avgta += ta[i] ;               // total turnaround time

}

System.out.println("\npid  arrival  brust  complete turn waiting");

for(int  i = 0 ; i< n;  i++)

{

System.out.println(pid[i] + "  \t " + ar[i] + "\t" + bt[i] + "\t" + ct[i] + "\t" + ta[i] + "\t"  + wt[i] ) ;

}

sc.close();

System.out.println("\naverage waiting time: "+ (avgwt/n));     // printing average waiting time.

System.out.println("average turnaround time:"+(avgta/n));    // printing average turnaround time.

}

}

sjf:

import java.util.*;

public class SJF {

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

System.out.println ("enter no of process:");

int n = sc.nextInt();

int pid[] = new int[n];

int at[] = new int[n]; // at means arrival time

int bt[] = new int[n]; // bt means burst time

int ct[] = new int[n]; // ct means complete time

int ta[] = new int[n]; // ta means turn around time

int wt[] = new int[n];  //wt means waiting time

int f[] = new int[n];  // f means it is flag it checks process is completed or not

int st=0, tot=0;

float avgwt=0, avgta=0;

for(int i=0;i<n;i++)

{

System.out.println ("enter process " + (i+1) + " arrival time:");

at[i] = sc.nextInt();

System.out.println ("enter process " + (i+1) + " brust time:");

bt[i] = sc.nextInt();

pid[i] = i+1;

f[i] = 0;

}

boolean a = true;

while(true)

{

int c=n, min=999;

if (tot == n) // total no of process = completed process loop will be terminated

break;

for (int i=0; i<n; i++)

{

/*

* If i'th process arrival time <= system time and its flag=0 and burst<min

* That process will be executed first

*/

if ((at[i] <= st) && (f[i] == 0) && (bt[i]<min))

{

min=bt[i];

c=i;

}

}

/* If c==n means c value can not updated because no process arrival time< system time so we increase the system time */

if (c==n)

st++;

else

{

ct[c]=st+bt[c];

st+=bt[c];

ta[c]=ct[c]-at[c];

wt[c]=ta[c]-bt[c];

f[c]=1;

tot++;

}

}

System.out.println("\npid  arrival brust  complete turn waiting");

for(int i=0;i<n;i++)

{

avgwt+= wt[i];

avgta+= ta[i];

System.out.println(pid[i]+"\t"+at[i]+"\t"+bt[i]+"\t"+ct[i]+"\t"+ta[i]+"\t"+wt[i]);

}

System.out.println ("\naverage tat is "+ (float)(avgta/n));

System.out.println ("average wt is "+ (float)(avgwt/n));

sc.close();

}

}

srtf:

import java.io.*;
public class SRTF {
 public static void main(String args[]) throws IOException
 {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int n;
      System.out.println("Please enter the number of Processes: ");
       n = Integer.parseInt(br.readLine());
       int proc[][] = new int[n + 1][4];//proc[][0] is the AT array,[][1] - RT,[][2] - WT,[][3] - TT
       for(int i = 1; i <= n; i++)
       {
      System.out.println("Please enter the Arrival Time for Process " + i + ": ");
      proc[i][0] = Integer.parseInt(br.readLine());
      System.out.println("Please enter the Burst Time for Process " + i + ": ");
      proc[i][1] = Integer.parseInt(br.readLine());
     }
       System.out.println();
     
       //Calculation of Total Time and Initialization of Time Chart array
     int total_time = 0;
     for(int i = 1; i <= n; i++)
     {
      total_time += proc[i][1];
     }
     int time_chart[] = new int[total_time];
     
     for(int i = 0; i < total_time; i++)
     {
      //Selection of shortest process which has arrived
      int sel_proc = 0;
      int min = 99999;
      for(int j = 1; j <= n; j++)
      {
       if(proc[j][0] <= i)//Condition to check if Process has arrived
       {
        if(proc[j][1] < min && proc[j][1] != 0)
        {
         min = proc[j][1];
         sel_proc = j;
        }
       }
      }
      
      //Assign selected process to current time in the Chart
      time_chart[i] = sel_proc;
      
      //Decrement Remaining Time of selected process by 1 since it has been assigned the CPU for 1 unit of time
      proc[sel_proc][1]--;
      
      //WT and TT Calculation
      for(int j = 1; j <= n; j++)
      {
       if(proc[j][0] <= i)
       {
        if(proc[j][1] != 0)
        {
         proc[j][3]++;//If process has arrived and it has not already completed execution its TT is incremented by 1
            if(j != sel_proc)//If the process has not been currently assigned the CPU and has arrived its WT is incremented by 1
             proc[j][2]++;
        }
        else if(j == sel_proc)//This is a special case in which the process has been assigned CPU and has completed its execution
         proc[j][3]++;
       }
      }
      
      //Printing the Time Chart
      if(i != 0)
      {
       if(sel_proc != time_chart[i - 1])
        //If the CPU has been assigned to a different Process we need to print the current value of time and the name of 
        //the new Process
       {
        System.out.print("--" + i + "--P" + sel_proc);
       }
      }
      else//If the current time is 0 i.e the printing has just started we need to print the name of the First selected Process
       System.out.print(i + "--P" + sel_proc);
      if(i == total_time - 1)//All the process names have been printed now we have to print the time at which execution ends
       System.out.print("--" + (i + 1));
      
     }
     System.out.println();
     System.out.println();
     
     //Printing the WT and TT for each Process
     System.out.println("P\t WT \t TT ");
     for(int i = 1; i <= n; i++)
     {
      System.out.printf("%d\t%2dms\t%2dms",i,proc[i][2],proc[i][3]);
      System.out.println();
     }
     
     System.out.println();
     
     //Printing the average WT & TT
     float WT = 0,TT = 0;
     for(int i = 1; i <= n; i++)
     {
      WT += proc[i][2];
      TT += proc[i][3];
     }
     WT /= n;
     TT /= n;
     System.out.println("The Average WT is: " + WT + "ms");
     System.out.println("The Average TT is: " + TT + "ms");
 }
    
}

RR:

// Java program for implementation of RR scheduling

public class GFG
{
   // Method to find the waiting time for all
   // processes
   static void findWaitingTime(int processes[], int n,
               int bt[], int wt[], int quantum)
   {
       // Make a copy of burst times bt[] to store remaining
       // burst times.
       int rem_bt[] = new int[n];
       for (int i = 0 ; i < n ; i++)
           rem_bt[i] = bt[i];
  
       int t = 0; // Current time
  
       // Keep traversing processes in round robin manner
       // until all of them are not done.
       while(true)
       {
           boolean done = true;
  
           // Traverse all processes one by one repeatedly
           for (int i = 0 ; i < n; i++)
           {
               // If burst time of a process is greater than 0
               // then only need to process further
               if (rem_bt[i] > 0)
               {
                   done = false; // There is a pending process
  
                   if (rem_bt[i] > quantum)
                   {
                       // Increase the value of t i.e. shows
                       // how much time a process has been processed
                       t += quantum;
  
                       // Decrease the burst_time of current process
                       // by quantum
                       rem_bt[i] -= quantum;
                   }
  
                   // If burst time is smaller than or equal to
                   // quantum. Last cycle for this process
                   else
                   {
                       // Increase the value of t i.e. shows
                       // how much time a process has been processed
                       t = t + rem_bt[i];
  
                       // Waiting time is current time minus time
                       // used by this process
                       wt[i] = t - bt[i];
  
                       // As the process gets fully executed
                       // make its remaining burst time = 0
                       rem_bt[i] = 0;
                   }
               }
           }
  
           // If all processes are done
           if (done == true)
           break;
       }
   }
  
   // Method to calculate turn around time
   static void findTurnAroundTime(int processes[], int n,
                           int bt[], int wt[], int tat[])
   {
       // calculating turnaround time by adding
       // bt[i] + wt[i]
       for (int i = 0; i < n ; i++)
           tat[i] = bt[i] + wt[i];
   }
  
   // Method to calculate average time
   static void findavgTime(int processes[], int n, int bt[],
                                       int quantum)
   {
       int wt[] = new int[n], tat[] = new int[n];
       int total_wt = 0, total_tat = 0;
  
       // Function to find waiting time of all processes
       findWaitingTime(processes, n, bt, wt, quantum);
  
       // Function to find turn around time for all processes
       findTurnAroundTime(processes, n, bt, wt, tat);
  
       // Display processes along with all details
       System.out.println("Processes " + " Burst time " +
                   " Waiting time " + " Turn around time");
  
       // Calculate total waiting time and total turn
       // around time
       for (int i=0; i<n; i++)
       {
           total_wt = total_wt + wt[i];
           total_tat = total_tat + tat[i];
           System.out.println(" " + (i+1) + "\t\t" + bt[i] +"\t " +
                           wt[i] +"\t\t " + tat[i]);
       }
  
       System.out.println("Average waiting time = " +
                       (float)total_wt / (float)n);
       System.out.println("Average turn around time = " +
                       (float)total_tat / (float)n);
   }
  
   // Driver Method
   public static void main(String[] args)
   {
       // process id's
       int processes[] = { 1, 2, 3};
       int n = processes.length;
  
       // Burst time of all processes
       int burst_time[] = {10, 5, 8};
  
       // Time quantum
       int quantum = 2;
       findavgTime(processes, n, burst_time, quantum);
   }
}


Related Solutions

Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
Programming language is Java In this second assignment, you will calculate currency conversions from United States...
Programming language is Java In this second assignment, you will calculate currency conversions from United States Dollars (USD) to Indian Rupees (INR) or to Euros (EUR) or to British Pounds (GB) using methods and formatting the results. Use these ratios: 1 USD to 72.282250 INR 1 USD to 0.913465 EUR 1 USD to 0.833335 GBP Your task is to write a program that • displays a menu to choose conversion from dollars to rupees, euros, or pounds. • displays the...
JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create...
JAVA programming - please answer all prompts as apart of 1 java assignment. Part A Create a java class InventoryItem which has a String description a double price an int howMany Provide a copy constructor in addition to other constructors. The copy constructor should copy description and price but not howMany, which defaults to 1 instead. In all inheriting classes, also provide copy constructors which chain to this one. Write a clone method that uses the copy constructor to create...
Programming Language : JAVA Create an interface named Turner, with a single method called turn(). Then...
Programming Language : JAVA Create an interface named Turner, with a single method called turn(). Then create 4 classes: 1- Leaf: that implements turn(), which changes the color of the Leaf object and returns true. If for any reason it is unable to change color, it should return false (you can come up with a reason for failure). The new color can be determined at random. 2- Document: that implements turn(), which changes the page on the document to the...
COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered...
COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered this week. come up with a “problem scenario” for which you can create a “solution”. Utilize any/all of the examples from the book and class that we discussed. Your program should be interactive and you should give a detailed statement about what the “description of the program – purpose and how to use it”. You should also use a “good bye” message. Remember to...
java Programming Problem 1: Reverse Characters Create an application ReverseCharacters in which you use an array-based...
java Programming Problem 1: Reverse Characters Create an application ReverseCharacters in which you use an array-based stack to read a sentence from the keyboard, and reverse the order of the letters in each word. Print the initial sentence, as well as the result of the reversal operation. Your Tasks: Using the information given in your textbook, create a class named ArrayBasedStack, that will help you solve the problem given above by providing the stack operations you need for this application....
Please answer the problem below in C programming language: Create a pointer activity source file -...
Please answer the problem below in C programming language: Create a pointer activity source file - cptr2.c - that takes two arguments, a number from 1 to 3, and a string sentence(s). Create variables for a character, an integer, a string pointer. Based on integer value you will use that number of string pointers. The string variable is a string pointer that has not been allocated.    Define pointers to those variables types without any initialization of those points to the...
This for Java Programming Write a java statement to import the java utilities. Create a Scanner...
This for Java Programming Write a java statement to import the java utilities. Create a Scanner object to read input. int Age;     Write a java statement to read the Age input value 4 . Redo 1 to 3 using JOptionPane
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT