Tuesday 14 April 2015

Concurrent Programming : Semaphore




What is Semaphores ?

A semaphore is a counter that controls the access to one or more shared resources. This mechanism is one of the basic tools of concurrent programming and is provided by most of the programming languages.

The concept of a semaphore was introduced by Edsger Dijkstra in 1965 and was used for the first time in the THEOS operating system

Example:-  Suppose there are three shared printer in your workspace and for each print request printer do printing. Question come here how shared resources has been access control over concurrent request, solution is “Semaphores”.
Semaphores has set of permit that access control over shared resources.  In our example there are three shared printer so we set three permit on semaphore, subsequently every access to shared resources semaphore decrement it values by one until values is greater than zero. Once it’s values is zero, Means all shared resources are busy and no more permit will be allowed until any resources is free. All requesting print commands will wait for release the resources.

Important Methods :

  Constructor :
  • Semaphore(int permits) :Creates a Semaphore with the given number of permits and nonfair fairness setting.
  • Semaphore(int permits, boolean fair) : -Creates a Semaphore with the given number of  permits and the given fairness setting
 Acquire() :-  Acquires a permit from this semaphore, blocking until one is available, or the thread is   interrupted.

 Release() :-  Releases a permit or increment permit by one, returning it to the semaphore.

Key Points:- 
     By default Fairness properties is false; means this class make no guarantees about the order in   which thread acquire permits.
  

Coding practices here : -




package com.semaphore.example;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SimplePrintQueue {

    private final Semaphore semaphore;
    private final int NO_OF_PRINTER = 3;

    public SimplePrintQueue() {
        semaphore = new Semaphore(NO_OF_PRINTER);
    }


    public void printJob(Object object) {
        try {
            semaphore.acquire();
            long duration = (long) (Math.random() * 10);
            System.out
                    .printf("%s: PrintQueue: Printing a Job in Printer  %d during %d seconds\n",
                            Thread.currentThread().getName(),
                            duration);
            TimeUnit.SECONDS.sleep(duration);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

    }
}



Job Runnable class 

package com.semaphore.example;
public class Job implements Runnable {
    private SimplePrintQueue printQueue;
    public Job(SimplePrintQueue q) {
        this.printQueue = q;
    }@Override public void run() {
        System.out.printf("%s: Going to print a job\n", Thread.currentThread().getName());
        printQueue.printJob(new Object());
        System.out.printf(" %s : The document has been printed \n", Thread.currentThread().getName());
    }
}



Main Program 

package com.semaphore.example;

public class Main {

    public static void main(String args[]) {
       
SimplePrintQueue printQueue = new SimplePrintQueue ();

        Thread thread[] = new Thread[50];
        for (int i = 0; i < 50; i++) {
            thread[i] = new Thread(new Job(printQueue), "Thread" + i);
        }

        for (int i = 0; i < 50; i++) {
            thread[i].start();
        }

    }

} 


No comments:

Post a Comment