Sunday, July 8, 2012

Semaphores in Java Example

Semaphores in java handles permits to execute the next lines of instructions. They are often use to restrict the number of threads to access a resource.

Before getting a resource the thread must acquire a permit form a semaphore and release the resource after using the shared resource which can be memory, storage or data.

Constructors

Semaphore ( i n t   permits )
Creates a Semaphore  with  the given  number of  permits and no fair fairness setting .
Semaphore ( i n t   permits ,   boolean   fair )
Creates a Semaphore  with  the given  number of  permits and the given  fairness setting .

Now for a sample semaphore program that counts until 20 using two threads that uses semaphores for data consistency.
Counter.java
import java.util.concurrent.Semaphore;
import javax.swing.JTextArea;

public class Counter extends Thread{
 private static int count=0;
 private String ID;
 private JTextArea TBox;
 private Semaphore sem;
 
 public ServiceQueue(String name,JTextArea jArea, Semaphore s){
  ID=name;
  TBox=jArea;
  sem=s;
 }
 
 private void nonCrit(int i){
  System.out.println(ID+" is not in critical: "+i);
 }
 
 
 private synchronized void doCrit(){
   count++;
   TBox.append(ID+" gave count: "+count+"\n");
 }
 
 public void run(){
  for(int ctr=0;ctr<10;ctr++){
  nonCrit(ctr);
   try{
   sem.acquire();
    } catch (InterruptedException e){ }
   doCrit();
   sem.release();
  }
 }
 
}
Executioner.java
import javax.swing.*;
import java.util.concurrent.Semaphore;
import java.awt.*;
public class Executioner extends JFrame{

 public Executioner(){
  super("Hello World");
  JTextArea TA=new JTextArea(20,15);
  Semaphore sem = new Semaphore(3, true);
  
  setLayout(new FlowLayout());
  add(TA);
  
  Counter Q1=new ServiceQueue("1st Class",TA,sem);
                Counter Q2=new ServiceQueue("3rd Class",TA,sem);
  
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setVisible(true);
  
  C1.start();
  C2.start();
  pack();
 }

 public static void main(String args[]){
  new Executioner();
 }
}

No comments:

Post a Comment