×

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another name for it. Scheduling in FCFS is quite similar to this. The round robin task scheduling and its use in a Java programme will be covered in this section.

Round Robin Algorithm

The preemptive process scheduling algorithm is called round robin scheduling. Every process is given a certain time to run cyclically. The term "fixed time" is also used for the concept of "time quantum," "time slot," and "time stamp." Once a process has run for a predetermined amount of time, it is preempted and another process runs for the remainder of that time. State-saving for preempted processes is accomplished by context switching. The algorithm's goal is to use the CPU as much as possible. The time sharing scheme is where the algorithm works best.

The Round Robin algorithm comes in the following three variations:

  • Deficit Round Robin
  • Selfish Round Robin
  • Skip Round Robin

We shall first comprehend the different temporal factors associated with the Round Robin algorithm's procedure before going on to the example.

Arrival Time: This refers to the instant that a process transitions into the ready state. It denotes that the procedure is prepared for use. It is determined by:

Response time is determined by subtracting the arrival time from the moment the process first receives the CPU.

Response Time: This is the period of time during which a process initially receives the CPU.

Turnaround Time: This is the length of time a procedure is carried out within the system. These formulae are used to compute it:

Turnaround Time = Completion Time - Arrival Time 

Waiting Time: This is the length of time required for a process to finish running. In other words, the amount of time a process spends waiting for the CPU while it is ready. It is calculated using the formula below:

            Waiting Time = Turnaround Time - Burst Time

Burst Time: The amount of time a process spends running on the CPU in total. Another name for it is execution time.

Completion Time: This is the length of time it takes for a procedure to be finished. It's also referred to as "exit time."

Throughput time: The quantity of tasks the CPU completes in a specific length of time is known as throughput time. It is employed to determine a CPU's efficiency.

 Benefits of Round Robin Scheduling

  • It has a cyclical structure.
  • Never does it result in famine.
  • The CPU performs each task for a set amount of time.
  • not giving any work a priority.
  • The schedule is similar to FCFS.

Round Robin Scheduling Java Program

public class Main
{
    // How to calculate the total waiting time?
    static void findWaitingTime(int processes[], int n,
                 int bt[], int wt[], int quantum)
    {
        // Create a duplicate of "burst times bt" to save any leftovers.
        // 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 going round-robin with the procedures.
        // until none of them have finished.
        while(true)
        {
            boolean done = true;
       
            //repeatedly go through each procedure one at a time
            for (int i = 0 ; i < n; i++)
            {
                // Whenever a process's burst time exceeds 0
                // then, just more processing is required.
                if (rem_bt[i] > 0)
                {
                    done = false; // There is a pending process
       
                    if (rem_bt[i] > quantum)
                    {
                        // The displays' value should be raised
                        // how long a procedure has been running
                        t += quantum;
       
                        // Reduce the current process's burst time.
                        // by quantum
                        rem_bt[i] -= quantum;
                    }
       
                    //if burst time falls within or matches
                    // Quantum. This process' final cycle
                    else
                    {
                        // The displays' value should be raised
                        // how long a procedure has been running
                        t = t + rem_bt[i];
       
                        // Current time less waiting time is the waiting time.
                        // used by this process
                        wt[i] = t - bt[i];
       
                        // As the procedure is completed
                        // set the time left for its blast to be 0
                        rem_bt[i] = 0;
                    }
                }
            }
       
            // if all operations are completed
            if (done == true)
              break;
        }
    }
       
    // Technique for estimating turnaround time
    static void findTurnAroundTime(int processes[], int n,
                            int bt[], int wt[], int tat[])
    {
        // By adding, you can determine turnaround time.
        // bt[i] + wt[i]
        for (int i = 0; i < n ; i++)
            tat[i] = bt[i] + wt[i];
    }
       
    // How to estimate the 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 determine how long each process will delay
        findWaitingTime(processes, n, bt, wt, quantum);
       
        //Calculate the turnaround time for each procedure.
        findTurnAroundTime(processes, n, bt, wt, tat);
       
        // Display procedures and any relevant information.
        System.out.println("Processes " + " Burst time +
                      " Waiting time " + " Turnaround 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 turnaround 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[] = {6,7, 8};
       
        // Time quantum
        int quantum = 2;
        findavgTime(processes, n, burst_time, quantum);
    }
}

Output:

Processes Burst time Waiting time Turnaround time
 1          6            12               18
 2          7            20               27
 3          8            13              21
Average waiting time = 15.0
Average turnaround time = 22

Related Topics

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.