KEMBAR78
Operating System Lab | PDF | Scheduling (Computing) | Computer Science
0% found this document useful (0 votes)
19 views65 pages

Operating System Lab

Uploaded by

god943381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views65 pages

Operating System Lab

Uploaded by

god943381
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Ex.

No:1 JOB SCHEDULING TECHNIQUES


Date:

Aim:
To write a java program to implement the concept of different job
scheduling techniques like,
a) First Come First Served [FCFS]
b) Shortest Job First [SJF]
c) Round Robin
d) Priority Scheduling
Algorithm:
a) First Come First Served

1.Get the number by jobs tobescheduled


2.Get the arrival time and service time of each and every job
3.Get the job according time as zeros for each job

4.Initialize the waiting time as zero for each job


5.Compute each job and find the average waiting by dividing total
compute each job and find number of job
a) Shortest Job First:
1. Get the number of jobs to be scheduled
2. Get the arrival time and service time of each job
3. sort the job according to its service time
4. Initialize the waiting time as zero for each job
c) Round Robin:
1. Get the number of jobs to be scheduled
2. Get the arrival time ,service time and time slice of each job
3. Sort the job according to its time of the arrival
4. Repeat the above steps in till all the jobs are completely serviced
d) Priority scheduling:
1. Get the number of jobs to be scheduled
2.Get the arrival time, service time and priority of every
3. Initialize the waiting time as zero for each jobs
4. While processing the jobs according to the started time and the service
time of the jobs being processed currently to the waiting time for each job
5. Compute the total waiting time by adding individual waiting time of the
each job and find the arrange time of job
Source code for FCFS:
import java.io.*;
class schedule
{
int hr,min,sec,ser,wait;
String name;
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
void get() throws IOException
{
System.out.println("enter process name:");
name = d.readLine();
System.out.println("enter the hour:");
hr =Integer.parseInt(d.readLine());
if(hr<=24)
{
System.out.println("enter the minutes");
min=Integer.parseInt(d.readLine());
if(min<=60)
{
System.out.println("enter the seconds:");
sec=Integer.parseInt(d.readLine());
if(sec<=60)
{
System.out.println("enter the service time:");
ser = Integer.parseInt(d.readLine());
}
else{
System.out.println("enter the seconds<=60");
sec=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the minutes<=60");
min=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the hours<=24");
hr =Integer.parseInt(d.readLine());
}
}
void put(){
System.out.println(""+name+"\t\t\t"+hr+":"+min+":"+sec+"\t\t\t"+ser+"\t
\t\t"+wait);
}
}
class fcfs {
public static void main(String[] args) throws IOException {
int i,j;
float total = 0.0f;
schedule s[], t;
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the number of processes:");
int n = Integer.parseInt(d.readLine());
s = new schedule [10];
t = new schedule();
for (i = 0; i < n; i++) {
s[i] = new schedule();
s[i].get();
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (s[i].hr > s[j].hr) {
t =s[i];
s[i] = s[j];
s[j] = t;
}
else if (s [i].hr == s[j].hr && s[i].min > s[j].min && s[i].sec > s[j].sec) {
t = s[i];
s[i] = s[ j];
s[j] =t;
} else
if (s[i].hr == s[j].hr && s[i].min > s[j].min && s[i].sec > s[j].sec) {
t = s[i];
s[i] = s[ j];
s[j] = t;
}
}
}
System.out.println("\nprocess\t\tstarting time\t\tservice time\t\twaiting
time");
for(i=0;i<n;i++){
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[i-1].ser;
total+=s[i].wait;
s[i].put();
}
System.out.println("\n total waiting time"+total); System.out.println("\n
average waiting time:"+(total/n));
}}
Source code for SJF:
import java.io.*;
class schedule{
int hr,min,sec,ser,wait;
int tot;
String name;
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
void get() throws IOException{
System.out.println("enter process name:");
name = d.readLine();
System.out.println("enter the hour:");
hr =Integer.parseInt(d.readLine());
if(hr<=24){
System.out.println("enter the minutes");
min=Integer.parseInt(d.readLine());
if(min<=60){
System.out.println("enter the seconds:");
sec=Integer.parseInt(d.readLine());
if(sec<=60){
System.out.println("enter the service time:");
ser = Integer.parseInt(d.readLine());
}else{
System.out.println("enter the seconds<=60");
sec=Integer.parseInt(d.readLine());
}
}else{
System.out.println("enter the minutes<=60");
min=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the hours<=24");
hr =Integer.parseInt(d.readLine());
}
tot=hr+min+sec;
}
void put(){
System.out.println(name+"\t\t\t"+hr+":"+min+":"+sec+"\t\t\t"+ser+"\t\t\t
"+wait);
}
}
public class sjf {
public static void main(String args[]) throws IOException {
// write your code here int i, j;
int i,j;
float total = 0.0f;
schedule s[], t;
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the number of processes:");
int n = Integer.parseInt(d.readLine());
s = new schedule [10];
t = new schedule();
for (i = 0; i < n ; i++) {
s[i] = new schedule();
s[i].get();
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (s[i].ser > s[j].ser)
{
t = s[i]; s[i] = s[j];
s[j] =t;
}
}
}
System.out.println("\nprocess\t\tstarting time\t\tservice time\t\twaiting
time");
for(i=0;i<n;i++){
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[ i-1].ser;
total+=s[i].wait;
s[i].put();
}
System.out.println("\n total waiting time"+total);
System.out.println("\n average waiting time:"+(total/n));
}
}
Source code for round robin:
import java.io.*;
class schedule{
int hr,min,sec,ser,wait;
String name;
BufferedReader d = new
BufferedReader(new InputStreamReader(System.in));
void get() throws IOException{
System.out.println("enter process name:");
name = d.readLine();
System.out.println("enter the hour:");
hr =Integer.parseInt(d.readLine());
if(hr<=24){
System.out.println("enter the minutes");
min=Integer.parseInt(d.readLine());
if(min<=60){
System.out.println("enter the seconds:");
sec=Integer.parseInt(d.readLine());
if(sec<=60){
System.out.println("enter the service time:");
ser = Integer.parseInt(d.readLine());
}else{
System.out.println("enter the seconds<=60");
sec=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the minutes<=60");
min=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the hours<=24");
hr =Integer.parseInt(d.readLine());
}
}
void put(){
System.out.println(""+name+"\t\t\t"+hr+":"+min+":"+sec+"\t\t\t"+ser+"\t
\t\t"+wait);
}
}
public class round{
public static void main(String[] args) throws IOException {
int i, j,k,round,max,ts,m1,w;
int mod[][]=new int[20][20]; int tser[]=new int [20]; float total = 0.0f;
schedule s[], t;
BufferedReader d =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the number of processes:");
int n = Integer.parseInt(d.readLine()); s = new schedule[10];
t = new schedule();
for (i = 0; i < n; i++) {
s[i] = new schedule(); s[i].get();
}
for (i = 0; i <n-1; i++) {
for (j = i + 1; j < n; j++) {
if (s[i].hr > s[j].hr) {
t = s[i]; s[i] = s[j];
s[j] = t;
}
else if (s[i].hr == s[j].hr && s[i].min > s[j].min) {
t = s[i];
s[i] = s[j]; s[j]= t;
} else if (s[i].hr == s[j].hr && s[i].min > s[j].min &&s[i].sec > s[j].sec) {
t = s[i]; s[i] = s[j]; s[j] = t;
}
}
}
System.out.println("enter the time slice:");
ts=Integer.parseInt(d.readLine());
max=0;
for(i=0;i<n;i++){
tser[i]=s[i].ser;
if(max<tser[i])
max=tser[i];
}
round = max/ts+1;
for(i=1;i<round;i++){
for(j=0;j<n;j++){
if(tser[j] !=0){
m1=tser[j]-ts;
if(m1>0){
mod[i][j]=ts;
tser[j]=tser[j]-ts;
}
else{
mod[i][j]=tser[j];
tser[j] =0;
}
}
else
mod [i][j]=0;
}
}
for(k=0;k<n;k++){
w=0;
s[k].wait=0;
for(i=1;i<round;i++){
if(mod[i][k] ==ts)
{
for(j=0;j<n;j++)
{
if(k!=j)
w=w+mod[ i][j];
}
}
else if(mod[i] [k]!=0)
for(j=0;j<k;j ++)
w=w+mod [i][j];
}
s[k].wait=w;
}
System.out.println("\nprocess\t\tstarting time\t\tservice time\t\twaiting
time");
for(i=0;i<n;i++){
total+=s[i].wait; s[i].put();
}
System.out.println("\n total waiting time"+total); System.out.println("\n
average waiting time:"+(total/n));
}
}
Source code for priority scheduling:
import java.io.*;
class schedule{
int hr,min,sec,ser,wait,pr; int tot;
String name;
BufferedReader d = new BufferedReader(new
InputStreamReader(System.in)); void get() throws IOException{
System.out.println("enter process name:"); name = d.readLine();
System.out.println("enter the hour:");
hr =Integer.parseInt(d.readLine());
if(hr<=24) {
System.out.println("enter the minutes");
min=Integer.parseInt(d.readLine());
if(min<=60){
System.out.println("enter the seconds:");
sec=Integer.parseInt(d.readLine());
if(sec<=60) {
System.out.println("enter the service time:"); ser =
Integer.parseInt(d.readLine());
System.out.println("enter the priority:");
pr = Integer.parseInt(d.readLine());
}else{
System.out.println("enter the seconds<=60");
sec=Integer.parseInt(d.readLine());
}
}else{
System.out.println("enter the minutes<=60");
min=Integer.parseInt(d.readLine());
}
}
else{
System.out.println("enter the hours<=24");
hr=Integer.parseInt(d.readLine());
}
tot = hr+min+sec;
}
void put(){
System.out.println(name+"\t\t"+hr+":"+min+":"+sec+"\t\t"+ser+"\t\t"+wai
t+ "\t "+pr);
}
}
public class priority{
public static void main(String[] args) throws IOException {
int i, j;
float total = 0.0f; schedule s[], t;
BufferedReader d =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the number of processes:");
int n = Integer.parseInt(d.readLine());
s = new schedule [10]; t = new schedule();
for (i = 0; i < n; i++) {
s[i] = new schedule(); s[i].get();
}
for (i = 0; i < n; i++){
for (j = i + 1; j < n; j++) {
if (s[i].pr > s[j].pr) {
t = s[i]; s[i] = s[j];
s[j]= t;
}
}
}
System.out.println("\nprocess\t starting time\t service time\twaiting
time\t priority");
for(i=0;i<n;i++){
if(i==0)
s[i].wait=0;
else
s[i].wait=s[i-1].wait+s[i-1].ser;
total+=s[i].wait; s[i].put();
}
System.out.println("total waiting time"+total);
System.out.println(" average waiting time:"+(total/n));
}
}
Sample input and Output:
FCFS:
ENTER THE NUMBER OF PROCESSES:4
ENTER PROCESS NAME: P1
ENTER THE HOUR: 2
ENTER THE MINUTES: 5
ENTER THE SECONDS: 3
ENTER THE SERVICE TIME: 1
ENTER THE PROCESS NAME: P2
ENTER THE HOUR: 4
ENTER THE MINUTES: 6
ENTER THE SECONDS: 3
ENTER THE SERVICE TIME:4
ENTER PROCESS NAME: P3
ENTER THE HOUR: 8
ENTER THE MINUTES: 3
ENTER THE SECONDS: 2
ENTER THE SERVICE TIME: 5
ENTER PROCESS NAME:P4
ENTER THE HOUR: 6
ENTER THE MINUTES: 3
ENTER THE SECONDS: 1
ENTER THE SERVICE TIME: 6
PROCESS STARTINGTIME SERVICE TIME WAITING TIME
PI 2:5:3 1 0
P2 4:6:3 4 1
P4 6:3:1 6 5
P3 8:3:2 5 11
TOTAL WAITING TIME:17.0
AVERAGE WAITING TIME:4.25
SJF:
ENTER THE NUMBER OF PROCESSES: 4
ENTER PROCESS NAME:P1
ENTER THE HOUR: 4
ENTER THE MINUTES: 5
ENTER THE SECONDS: 3
ENTER THE SERVICE TIME: 2
ENTER THE PROCESS NAME: P2
ENTER THE HOUR:2
ENTER THE MINUTES:1
ENTER THE SECONDS: 0
ENTER THE SERVICE TIME:4
ENTER PROCESS NAME:P3
ENTER THE HOUR:3
ENTER THE MINUTES:5
ENTER THE SECONDS:2
ENTER THE SERVICE TIME:7
ENTER PROCESS NAME:P4
ENTER THE HOUR:5
ENTER THE MINUTES:2
ENTER THE SECONDS:1
ENTER THE SERVICE TiME:4
PROCESS STARTING TIME SERVICE TIME WAITING TIME
P1 4:5:3 2 0
P2 2:1:0 4 2
P4 5:2:1 4 6
P3 3:5:2 7 10

TOTAL WAITING TiME:18.0


AVERAGE WAITING TIME:4.5
Round Robin:
ENTER THE NUMBER OF PROCESSES:4
ENTER PROCESS NAME:P1
ENTER THE HOUR:1
ENTERTHEMiNUTES:1
ENTERTHE SECONDS: 1
ENTER THE SERVICE TiME:1
ENTER THE PROCESS NAME:P2
ENTER THE HOUR:2
ENTER THE MiNUTES:2
ENTER THE SECONDS:2
ENTER THE SERVICE TiME:2
ENTER PROCESS NAME:P3
ENTER THE HOUR:3
ENTER THE MiNUTES:3
ENTER THE SECONDS:3
ENTER THE SERVICE TiME:3
ENTER PROCESS NAME:P4
ENTER THE HOUR:4
ENTER THE MiNUTES:4
ENTER THE SECONDS:4
ENTER THE SERVICE TiME:4
Enter the time slice:3
PROCESS STARTING TIME SERVICE TIME WAITING TIME
PI 1:1:1 1 0
P2 2:2:2 2 1
P3 3:3:3 3 6
P4 4:4:4 4 6

TOTAL WAITING TIME:13.0 AVERAGE WAITING TIME:3.25


Priority Scheduling:
ENTER THE NUMBEROFPROCESSES:4
ENTER PROCESS NAME:P1
ENTER THE HOUR:1
ENTER THE MINUTES:2
ENTER THE SECONDS:3
ENTER THE SERVICE TIME:4
ENTER THE PRIORITY:3
ENTER THE PROCESS NAME:P2
ENTER THE HOUR:2
ENTER THE MINUTES:5
ENTER THE SECONDS:6
ENTER THE SERVICE TIME:3
ENTERTHE PRIORITY:2
ENTER PROCESS NAME: P3
ENTERTHE HOUR:6
ENTER THE MiNUTES:2
ENTER THE SECONDS: 1
ENTER THE SERVICE TiME:6
ENTER THE PRIORITY: 1
ENTER PROCESS NAME:P4
ENTER THE HOUR:7
ENTER THE MINUTES:
ENTER THE SECONDS:1
ENTER THE SERVICETIME:
ENTER THE PRiORiTY:4
PROCESS STARTINGTIME SERVICETIME WAITINGTIME PRIORITY
P3 6:2:1 6 0 1
P2 2:5:6 3 6 2
PI 1:2:3 4 9 3
P4 7:3:1 56 13 4

TOTAL WAITING TIME:28.0


AVERAGE WAITING TiME:7.0

Result:
Thus the java program to implement the scheduling techniques was
created, executed successfully and the output was job verified
Ex No: 2 DISK SCHEDULING TECHNIQUES

Date:

Aim:

To write a java program to implement the concept of different disk


scheduling techniques like,

a.First Come First Server [FCFS]

b.Shortest Seek Time First [SSTF]

c.Scan

d.C-Scan

e.Look

f.C-Look

Algorithm:

a.Let Request array represents an array storing indexes of tracks that have been
requested in ascending order of their time of arrival. ‘head’ is the position of
disk head.

b.Let us one by one take the tracks in default order and calculate the absolute
distance of the track from the head.

c.Increment the total seek count with this distance.

d.Currently serviced track position now becomes the new head position.

e.Go to step 2 until all tracks in request array have not been serviced.
Source code for fcfs:

class FCFS
{
static int size = 8;
static void FCFS(int arr[], int head)
{
int seek_count = 0;
int distance, cur_track;
for (int i = 0; i < size; i++)
{
cur_track = arr[i];
distance = Math.abs(cur_track - head);
seek_count += distance;
head = cur_track;
}
System.out.println("Total number of " + "seek operations = " +
seek_count);
System.out.println("Seek Sequence is");
for (int i = 0; i < size; i++)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String[] args)
{
int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
FCFS(arr, head);
}
}
Sample input and output:

FCFS:

Total number of seek operations = 510


Seek Sequence is: 176 79 34 60 92 11 41 114
B.Shortest Seek Time First [SSTF]

Algorithm:

a.Let Request array represents an array storing indexes of tracks that have been
requested. ‘head’ is the position of disk head.

b.Find the positive distance of all tracks in the request array from head.

c.Find a track from requested array which has not been accessed/serviced yet
and has minimum distance from head.

d.Increment the total seek count with this distance.

e.Currently serviced track position now becomes the new head position.

f.Go to step 2 until all tracks in request array have not been serviced.

Source code for SSTF:

class node {
int distance = 0;
boolean accessed = false;
}
public class SSTF {
public static void calculateDifference(int queue[], int head, node diff[])
{
for (int i = 0; i < diff.length; i++)
diff[i].distance = Math.abs(queue[i] - head);
}
public static int findMin(node diff[])
{
int index = -1, minimum = Integer.MAX_VALUE;
for (int i = 0; i < diff.length; i++) {
if (!diff[i].accessed && minimum > diff[i].distance) {
minimum = diff[i].distance;
index = i;
}
}
return index;
}
public static void shortestSeekTimeFirst(int request[], int head)
{
if (request.length == 0)
return;
node diff[] = new node[request.length];
for (int i = 0; i < diff.length; i++)
diff[i] = new node();
int seek_count = 0;
int[] seek_sequence = new int[request.length + 1];
for (int i = 0; i < request.length; i++) {
seek_sequence[i] = head;
calculateDifference(request, head, diff);
int index = findMin(diff);
diff[index].accessed = true;
seek_count += diff[index].distance;
head = request[index];
}
seek_sequence[seek_sequence.length - 1] = head;
System.out.println("Total number of seek operations = "
+ seek_count);
System.out.println("Seek Sequence is");
for (int i = 0; i < seek_sequence.length; i++)
System.out.print(seek_sequence[i]+" ");
}
public static void main(String[] args){
int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 };
shortestSeekTimeFirst(arr, 50);
}}

Output for SSTF:


SSTF:
Total number of seek operations = 204
Seek Sequence is
50 41 34 11 60 79 92 114 176
C.Scan

Algorithm:

a. Let Request array represents an array storing indexes of tracks that have
been requested in ascending order of their time of arrival. ‘head’ is the
position of disk head.

b. Let direction represents whether the head is moving towards left or right.

c. In the direction in which head is moving service all tracks one by one.

d. Calculate the absolute distance of the track from the head.

e. Increment the total seek count with this distance.

f. Currently serviced track position now becomes the new head position.

g. Go to step 3 until we reach at one of the ends of the disk.

h. If we reach at the end of the disk reverse the direction and go to step 2
until all tracks in request array have not been serviced.

Source code for SCAN:

import java.util.*;

class scan

static int size = 8;

static int disk_size = 200;

static void SCAN(int arr[], int head, String direction)

int seek_count = 0;

int distance, cur_track;

Vector<Integer> left = new Vector<Integer>(),


right = new Vector<Integer>(); Vector<Integer> seek_sequence = new
Vector<Integer>();

if (direction == "left")

left.add(0);

else if (direction == "right")

right.add(disk_size - 1);

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

if (arr[i] < head)

left.add(arr[i]);

if (arr[i] > head)

right.add(arr[i]);

// sorting left and right vectors

Collections.sort(left);

Collections.sort(right);

int run = 2;

while (run-- >0)

if (direction == "left")

for (int i = left.size() - 1; i >= 0; i--)

cur_track = left.get(i);
seek_sequence.add(cur_track);

// calculate absolute distance

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

direction = "right";

else if (direction == "right")

for (int i = 0; i < right.size(); i++)

cur_track = right.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

direction = "left";

System.out.print("Total number of seek operations = " + seek_count + "\n");

System.out.print("Seek Sequence is" + "\n");

for (int i = 0; i < seek_sequence.size(); i++)


{

System.out.print(seek_sequence.get(i) + " ");

public static void main(String[] args)

int arr[] = { 176, 79, 34, 60,92, 11, 41, 114 };

int head = 50;

String direction = "left";

SCAN(arr, head, direction);

}
Output for scan :
Total number of seek operations = 226
Seek Sequence is
41 34 11 0 60 79 92 114 176
D.C-Scan

Algorithm:

a. Let Request array represents an array storing indexes of tracks that

have been requested in ascending order of their time of arrival.

‘head’ is the position of disk head.

b. The head services only in the right direction from 0 to size of the disk.

c. While moving in the left direction do not service any of the tracks.

d. When we reach at the beginning(left end) reverse the direction.


e. While moving in right direction it services all tracks one by one.

f. While moving in right direction calculate the absolute distance of the track
from the head.

g. Increment the total seek count with this distance.

h. Currently serviced track position now becomes the new head position.

i. Go to step 6 until we reach at right end of the disk.

j. If we reach at the right end of the disk reverse the direction and go to step
3 until all tracks in request array have not been serviced.

Source code for C-Scan:

// C-SCAN Disk Scheduling algorithm

import java.util.*;

class c_scan {

static int size = 8;

static int disk_size = 200;

public static void CSCAN(int arr[], int head)

int seek_count = 0;

int distance, cur_track;

Vector<Integer> left = new Vector<Integer>();

Vector<Integer> right = new Vector<Integer>();

Vector<Integer> seek_sequence

= new Vector<Integer>();

left.add(0);

right.add(disk_size - 1);
for (int i = 0; i < size; i++) {

if (arr[i] < head)

left.add(arr[i]);

if (arr[i] > head)

right.add(arr[i]);

Collections.sort(left);

Collections.sort(right);

for (int i = 0; i < right.size(); i++) {

cur_track = right.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

head = 0;

seek_count += (disk_size - 1);

for (int i = 0; i < left.size(); i++) {

cur_track = left.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

}
System.out.println("Total number of seek " + "operations = " + seek_count);

System.out.println("Seek Sequence is");

for (int i = 0; i < seek_sequence.size(); i++) {

System.out.print(seek_sequence.get(i)+” ”);

public static void main(String[] args) throws Exception

int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 };

int head = 50;

System.out.println("Initial position of head: "+ head);

CSCAN(arr, head);

Output:
Initial position of head: 50
Total number of seek operations = 389
Seek Sequence is
60 79 92 114 176 199 0 11 34 41
E.Look

Algorithm:

a. Let Request array represents an array storing indexesof tracks that

have been requested in ascending order of their time of arrival.

‘head’ is the position of disk head.


b. The initial direction in which head is moving is given and it services in the
same direction.

c. The head services all the requests one by one in the direction head is moving.

d. The head continues to move in the same direction until all the request in this
direction are finished.

e. While moving in this direction calculate the absolute distance of the track
from the head.

f. Increment the total seek count with this distance.

g. Currently serviced track position now becomes the new head position.

h. Go to step 5 until we reach at last request in this direction.

i. If we reach where no requests are needed to be serviced in this direction


reverse the direction and go to step 3 until all tracks in request array have
not been serviced.

Source code for Look:

import java.util.*;

class Look{

static int size = 8;

static int disk_size = 200;

public static void LOOK(int arr[], int head, String direction)

int seek_count = 0;

int distance, cur_track;

Vector<Integer> left = new Vector<Integer>();

Vector<Integer> right = new Vector<Integer>();

Vector<Integer> seek_sequence = new Vector<Integer>();


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

if (arr[i] < head)

left.add(arr[i]);

if (arr[i] > head)

right.add(arr[i]);

Collections.sort(left);

Collections.sort(right);

int run = 2;

while (run-- > 0)

if (direction == "left")

for(int i = left.size() - 1;

i >= 0; i--)

cur_track = left.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

direction = "right";
}

else if (direction == "right")

for(int i = 0; i < right.size(); i++)

cur_track = right.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

direction = "left";

System.out.println("Total number of seek " +

"operations = " + seek_count);

System.out.println("Seek Sequence is");

for(int i = 0; i < seek_sequence.size(); i++)

System.out.print(seek_sequence.get(i)+” ”);

public static void main(String[] args) throws Exception

{
int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 };

int head = 50;

String direction = "right"; System.out.println("Initial position of head:


"+head);

LOOK(arr, head, direction);

}
Output:
Initial position of head: 50
Total number of seek operations = 291
Seek Sequence is:
60 79 92 114 176 41 34 11
E.C-Look

Algorithm:

a. Let Request array represents an array storing indexes of the tracks that
have been requested in ascending order of their time of arrival and head is
the position of the disk head.

b. The initial direction in which the head is moving is given and it services in
the same direction.

c. The head services all the requests one by one in the direction it is moving.

d. The head continues to move in the same direction until all the requests in
this direction have been serviced.

e. While moving in this direction, calculate the absolute distance of the


tracks from the head.

f. Increment the total seek count with this distance.

g. Currently serviced track position now becomes the new head position.
h. Go to step 5 until we reach the last request in this direction.

i. If we reach the last request in the current direction then reverse the
direction and move the head in this direction until we reach the last
request that is needed to be serviced in this direction without servicing the
intermediate requests.

j. Reverse the direction and go to step 3 until all the requests have not been
serviced.

Source code for C-Look:

import java.util.*;

class c_look{

static int size = 8;

static int disk_size = 200;

public static void CLOOK(int arr[], int head)

int seek_count = 0;

int distance, cur_track;

Vector<Integer> left = new Vector<Integer>();

Vector<Integer> right = new Vector<Integer>();

Vector<Integer> seek_sequence = new Vector<Integer>();

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

if (arr[i] < head)

left.add(arr[i]);

if (arr[i] > head)

right.add(arr[i]);
}

Collections.sort(left);

Collections.sort(right);

for(int i = 0; i < right.size(); i++)

cur_track = right.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

seek_count += Math.abs(head - left.get(0));

head = left.get(0);

for(int i = 0; i < left.size(); i++)

cur_track = left.get(i);

seek_sequence.add(cur_track);

distance = Math.abs(cur_track - head);

seek_count += distance;

head = cur_track;

System.out.println("Total number of seek " +

"operations = " + seek_count);

System.out.println("Seek Sequence is");


for(int i = 0; i < seek_sequence.size(); i++)

System.out.print(seek_sequence.get(i)+” “);

public static void main(String []args)

int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 };

int head = 50;

System.out.println("Initial position of head: " +

head);

CLOOK(arr, head);

OUTPUT:
Initial position of head: 50
Total number of seek operations = 321
Seek Sequence is
60 79 92 114 176 11 34 41

Result:
Thus the java program to implement the disk scheduling techniques was
created,executed successfully and the output was verified.
EX No.3 DINING PHILOSOPHER PROBLEM

Date:

AIM:

To write a java program to implement the concept of the Dining


philosopher problem.

Algorithm:

1.Get the total number of philosopher

2.Get the number of philosopher who are hungry

3.if all are hungry then deadlock who are hungry

4.get the philosopher position

5. display the menu

6.two can eat at a time

7.one can eat at a time

8.if choice is one,then

a.get the philosopher states of eating position

b.display the means of those who are waiting

Source code:

import java.util.concurrent.Semaphore;

import java.util.concurrent.ThreadLocalRandom;

public class DiningPhilosophers {

static int philosophersNumber = 5;

static Philosopher philosophers[] = new Philosopher[philosophersNumber];

static Fork forks[] = new Fork[philosophersNumber];

static class Fork {


public Semaphore mutex = new Semaphore(1);

void grab() {

try {

mutex.acquire();

catch (Exception e) {

e.printStackTrace(System.out);

void release() {

mutex.release();

boolean isFree() {

return mutex.availablePermits() > 0;

static class Philosopher extends Thread {

public int number;

public Fork leftFork;

public Fork rightFork;

Philosopher(int num, Fork left, Fork right) {

number = num;

leftFork = left;

rightFork = right;
}

public void run(){

System.out.println("Hi! I'm philosopher #" + number);

while (true) {

leftFork.grab();

System.out.println("Philosopher #" + number + " grabs left fork.");

rightFork.grab();

System.out.println("Philosopher #" + number + " grabs right fork.");

eat();

leftFork.release();

System.out.println("Philosopher #" + number + " releases left fork.");

rightFork.release();

System.out.println("Philosopher #" + number + " releases right fork.");

void eat() {

try {

int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);

System.out.println("Philosopher #" + " eats for " + sleepTime);

Thread.sleep(sleepTime);

catch (Exception e) {

e.printStackTrace(System.out);

}
}

public static void main(String args[]) {

System.out.println("Dining philosophers problem.");

for (int i = 0; i < philosophersNumber; i++) {

forks[i] = new Fork();

for (int i = 0; i < philosophersNumber; i++) {

philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) %


philosophersNumber]);

philosophers[i].start();

while (true) {

try {

// sleep 1 sec

Thread.sleep(1000);

// check for deadlock

boolean deadlock = true;

for (Fork f : forks) {

if (f.isFree()) {

deadlock = false;

break;

}
if (deadlock) {

Thread.sleep(1000);

System.out.println("Hurray! There is a deadlock!");

break;

catch (Exception e) {

e.printStackTrace(System.out);

System.out.println("Bye!");

System.exit(0);

Sample output:

Dining philosophers problem.

Hi! I'm philosopher #0

Hi! I'm philosopher #3

Philosopher #3 grabs left fork.

Hi! I'm philosopher #4

Philosopher #0 grabs left fork.

Hi! I'm philosopher #1

Hi! I'm philosopher #2


Philosopher #0 grabs right fork.

Philosopher #3 grabs right fork.

Philosopher #2 grabs left fork.

Philosopher # eats for 806

Philosopher # eats for 820

Philosopher #0 releases left fork.


Philosopher #1 grabs left fork.
Philosopher #0 releases right fork.
Philosopher #0 grabs left fork.
Philosopher #2 grabs right fork.
Philosopher #3 releases left fork.
Philosopher #3 releases right fork.
Philosopher # eats for 96
Philosopher #4 grabs left fork.
Philosopher #1 grabs right fork.
Philosopher # eats for 57
Philosopher #2 releases left fork.
Philosopher #3 grabs left fork.
Philosopher #2 releases right fork.
Philosopher #0 grabs right fork.
Philosopher # eats for 795
Philosopher #1 releases left fork.
Philosopher #2 grabs left fork.
Philosopher #1 releases right fork.
Philosopher #4 grabs right fork.
Philosopher # eats for 981
Philosopher #0 releases left fork.
Philosopher #1 grabs left fork.
Philosopher #0 releases right fork.
Hurray! There is a deadlock!
Bye!

Result:

Thus the java program to implement the dining philosopher problem was
created,executed successfully and the output was verified
Ex No:4 PRODUCER CONSUMER PROBLEM
Date:

Aim:

To Write a java program to implement the concept of the producer consumer


problem

Algorithm:

1. Start
2. Define the maximum buffer size.
3.Enter the number of producers and consumers.
4. The producer produces the job and put it in the buffer.
5.The consumer takes the job from the buffer.
6.If the buffer is full the producer goes to sleep.
7.If the buffer is empty then consumer goes to sleep.
8.Stop

Source code:

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

public class Main

public static final String ANSI_RED = "\u001B[31m";

public static final String ANSI_BLUE = "\u001B[34m";

public static final String ANSI_PURPLE = "\u001B[35m";

public static void main (String[]args)

{
List < String > buffer = new ArrayList <> ();

Producer producer = new Producer (buffer, Main.ANSI_PURPLE);

Consumer consumer1 = new Consumer (buffer, Main.ANSI_BLUE);

Consumer consumer2 = new Consumer (buffer, Main.ANSI_RED);

new Thread (producer).start ();

new Thread (consumer1).start ();

new Thread (consumer2).start ();

class Producer implements Runnable

private final List < String > buffer;

private final String color;

public Producer (List < String > buffer, String color)

this.buffer = buffer;

this.color = color;

@Override public void run ()

Random random = new Random ();

String[]nums = {"1", "2", "3", "4", "5"};

for (String num:nums){

try
{

System.out.println (color + "Adding...." + num);

synchronized (buffer)

buffer.add (num);

Thread.sleep (random.nextInt (1000));


}
catch (InterruptedException e)
{
System.out.println ("Producer was interrupted.");
}
}
System.out.println ("Adding EOF and exiting....");
synchronized (buffer)
{
buffer.add ("EOF");
}
}
}
class Consumer implements Runnable
{
private List < String > buffer;
private String color;
public Consumer (List < String > buffer, String color)
{
this.buffer = buffer;
this.color = color;
}
public void run ()
{
while (true)
{
synchronized (buffer)
{
if (buffer.isEmpty ())
{
continue;
}
if (buffer.get (0).equals ("EOF"))
{
System.out.println (color + "Exiting...");
break;
}
else
{
System.out.println (color + "Removed " + buffer.remove (0));
}
}

}
}
}
output:
_[35mAdding....1
_[31mRemoved 1
_[35mAdding....2
_[34mRemoved 2
_[35mAdding....3
_[34mRemoved 3
_[35mAdding....4
_[31mRemoved 4
_[35mAdding....5
_[34mRemoved 5
Adding EOF and exiting....

_[34mExiting...

_[31mExiting...

Result:

Thus the java program to implement the producer consumer problem was
created,executed successfully and the output was verified.
Ex No:5 BANKERS ALGORITHM

Date:

Aim:

To write a java program to implement Bankers algorithm

Algorithm:

Set number of process n=5

set number of resources m= 3

when a request for resources is made by process n then following


action are taken

 if requestb<= available go to step 3

 the system pretend to have allocated the resource to n

Source code:

public class GfGBankers

int n = 5; // Number of processes

int m = 3; // Number of resources

int need[][] = new int[n][m];

int [][]max;

int [][]alloc;

int []avail;

int safeSequence[] = new int[n];

void initializeValues()

// P0, P1, P2, P3, P4 are the Process names here


// Allocation Matrix

alloc = new int[][] { { 0, 1, 0 }, //P0

{ 2, 0, 0 }, //P1

{ 3, 0, 2 }, //P2

{ 2, 1, 1 }, //P3

{ 0, 0, 2 } }; //P4

// MAX Matrix

max = new int[][] { { 7, 5, 3 }, //P0

{ 3, 2, 2 }, //P1

{ 9, 0, 2 }, //P2

{ 2, 2, 2 }, //P3

{ 4, 3, 3 } }; //P4

// Available Resources

avail = new int[] { 3, 3, 2 };

void isSafe()

int count=0;

//visited array to find the already allocated process

boolean visited[] = new boolean[n];

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

visited[i] = false;

}
//work array to store the copy of available resources

int work[] = new int[m];

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

work[i] = avail[i];

while (count<n)

boolean flag = false;

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

if (visited[i] == false)

int j;

for (j = 0;j < m; j++)

if (need[i][j] > work[j])

break;

if (j == m)

safeSequence[count++]=i;

visited[i]=true;

flag=true;
for (j = 0;j < m; j++)

work[j] = work[j]+alloc[i][j];

if (flag == false)

break;

if (count < n)

System.out.println("The System is UnSafe!");

else

//System.out.println("The given System is Safe");

System.out.println("Following is the SAFE Sequence");

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

System.out.print("P" + safeSequence[i]);

if (i != n-1)
System.out.print(" -> ");

void calculateNeed()

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

for (int j = 0;j < m; j++)

need[i][j] = max[i][j]-alloc[i][j];

public static void main(String[] args)

int i, j, k;

GfGBankers gfg = new GfGBankers();

gfg.initializeValues();

//Calculate the Need Matrix

gfg.calculateNeed();

// Check whether system is in safe state or not

gfg.isSafe();

}
}

Output:

Following is the SAFE Sequence

P1 -> P3 -> P4 -> P0 -> P2

Result:

Thus ths java program to implement the bankers algorithm was


created,executed successfully and the output was verified.
Ex No: MEMORY ALLOCATION

Date:

Aim:

To Write a java program to implement the concept of different memory


allocation

a.First fit

b.Best fit

c.Worst fit

d.Next fit

Algorithm for first fit:

1.Get the number of process and number of blocks.Step 2.Get the size of each
block.

3. Allocate process If (size of the block > = size of the process)

//allocate the process

else

//move on to the next blog

4.Display the process with the blocks allocated to a respective process

5.Stop

Source code for first fit:

class GFG

static void firstFit(int blockSize[], int m,

int processSize[], int n)

{
int allocation[] = new int[n];

for (int i = 0; i < allocation.length; i++)

allocation[i] = -1;

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

for (int j = 0; j < m; j++)

if (blockSize[j] >= processSize[i])

allocation[i] = j;

blockSize[j] -= processSize[i];

break;

System.out.println("\nProcess No.\tProcess Size\tBlock no.");

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

System.out.print(" " + (i+1) + "\t\t" +

processSize[i] + "\t\t");

if (allocation[i] != -1)

System.out.print(allocation[i] + 1);

else

System.out.print("Not Allocated");
System.out.println();

public static void main(String[] args)

int blockSize[] = {100, 500, 200, 300, 600};

int processSize[] = {212, 417, 112, 426};

int m = blockSize.length;

int n = processSize.length;

firstFit(blockSize, m, processSize, n);

Output for first fit:

Process No. Process Size Block no.

1 212 2

2 417 5

3 112 2

4 426 Not Allocated

Algorithm for best fit:

1.Get the number of process and number of blocks.Step 2.Get the size of each
block.

3. Allocate process

4.Display the process with the blocks allocated to a respective process

5.Stop
Source code for best fit:

public class GFG

static void bestFit(int blockSize[], int m, int processSize[],int n)

int allocation[] = new int[n];

for(int i = 0; i < allocation.length; i++)

allocation[i] = -1;

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

int bestIdx = -1;

for (int j=0; j<m; j++)

if (blockSize[j] >= processSize[i])

if (bestIdx == -1)

bestIdx = j;

else if (blockSize[bestIdx] > blockSize[j])

bestIdx = j;

if (bestIdx != -1)

allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];

System.out.println("\nProcess No.\tProcess Size\tBlock no.");

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

System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t");

if (allocation[i] != -1)

System.out.print(allocation[i] + 1);

else

System.out.print("Not Allocated");

System.out.println();

public static void main(String[] args)

int blockSize[] = {100, 500, 200, 300, 600};

int processSize[] = {212, 417, 112, 426};

int m = blockSize.length;

int n = processSize.length;

bestFit(blockSize, m, processSize, n);

}
Output for best fit:

Process No. Process Size Block no.

1 212 4

2 417 2

3 112 3

4 426 5

Result:

Thus the java program to implement the memory allocation techniques was
created and executed successfull

You might also like