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

Java Programming In this assignment we are going to create our own programming language, and process...
Java Programming In this assignment we are going to create our own programming language, and process it Java. programming language has 6 commands enter add subtract multiply divide return enter, add, subtract, multiply, divide all take 1 parameter (a double value). return takes no parameters.
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...
Using the Java programming language: Create and implement a class Car that models a car. A...
Using the Java programming language: Create and implement a class Car that models a car. A Car is invented to have a gasoline tank that can hold a constant max of 12.5 gallons, and an odometer that is set to 0 for a new car. All cars have an original fuel economy of 23.4 miles per gallon, but the value is not constant. Provide methods for constructing an instance of a Car (one should be zero parameter, and the other...
Code in C Instructions For this programming assignment you are going to implement a simulation of...
Code in C Instructions For this programming assignment you are going to implement a simulation of Dijkstra’s solution to the Dining Philosophers problem using threads, locks, and condition variables. Dijkstra’s Solution Edsgar Dijkstra’s original solution to the Dining Philosophers problem used semaphores, but it can be adapted to use similar mechanisms: • Each philosopher is in one of three states: THINKING, HUNGRY, or EATING. • Every philosopher starts out in the THINKING state. • When a philosopher is ready to...
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...
Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and...
Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period of time approximates the typical pid usage in which a pid is assigned to a new process, the process executes and then terminates, and the pid is released on the process's termination.) On UNIX and Linux systems, sleeping is accomplished through...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT