FIFO Page Replacement Algorithm in Java

FIFO in OS

FIFO Page Replacement Algorithm in Java

 

The approach of First in First Out (FIFO) states that the element which entered the queue initially will leave the queue first. The order in which the elements are placed in a queue will be followed to remove them from the queue. 

 Specifically, the element present at the bottom of the queue will be removed first. This also means that the element present on the top of the queue will be removed last.

Program in Java

// Java program for FIFO page replacement in the Operating Systems.

import java.util.HashSet;

import java.util.LinkedList;

import java.util.Queue;

Class PerpInsta

{

    // Function to find page faults using FIFO

    static int pageFaults(int pages[], int n, int capacity)

    {

     // For the representation of current pages, an unordered_set is used. The method helps to check if the page is present or not

        HashSet s = new HashSet<>(capacity);

             // Code to store the pages following the FIFO approach

        Queue indexes = new LinkedList<>() ;
      

        // Starting from the initial page

        int page_faults = 0;

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

        {

            // Checking the capacity of the set for more pages

            if (s.size() < capacity)

            {

                // Insert page if it is not present in the set

                if (!s.contains(pages[i]))

                {
                    s.add(pages[i]);

       
                   // incrementing the page fault counter

                    page_faults++;

       
                    // Code to push the current page in the queue

                    indexes.add(pages[i]);

                }

            }
      

           // FIFO is carried out if the set is full
        

            else

            {

               // Check whether the page in demand is not present in the set

                
                if (!s.contains(pages[i]))

                {

                    //Remove the first page from the queue

                    int val = indexes.peek();  

                    indexes.poll();

                  // Pop the index page

                    s.remove(val);
 

                    // Push the current page

                    s.add(pages[i]);
           

                    indexes.add(pages[i]);


                   // Increment page fault counter

                    page_faults++;

                }

            }

        }

       
        return page_faults;

    }

      

   // Driver method

    public static void main(String args[])

    {

        int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};

        int capacity = 4;

        System.out.println(pageFaults(pages, pages.length, capacity));

    }

}

Output

7