001 /* 002 * $Id: Semaphore.java,v 1.7 2004/01/17 12:19:18 kredel Exp $ 003 */ 004 005 //package edu.unima.ky.parallel; 006 package thread; 007 008 import util.Logger; 009 010 import java.io.Serializable; 011 //import org.apache.log4j.Logger; 012 013 /** 014 * Semaphore. 015 * This class is safe against Thread InterruptedException. 016 * @author Akitoshi Yoshida 017 * @author Heinz Kredel. 018 */ 019 public class Semaphore implements Serializable { 020 private int init; 021 private int s; 022 private int del; 023 024 //private static Logger logger = Logger.getLogger("edu.jas"); 025 private static Logger logger = new Logger(); 026 027 /** 028 * Constructs a default semaphore. 029 */ 030 public Semaphore() { 031 this(0); 032 } 033 034 /** 035 * Constructs a semaphore with the given upper limit value. 036 * @param i initial limit. 037 */ 038 public Semaphore(int i) { 039 if (i >=0) { init = i; } else { init = 0; } 040 s = init; 041 del = 0; 042 } 043 044 /** 045 * Finalizes this object. 046 */ 047 protected void finalize() throws Throwable { 048 if (init != s) { 049 int x = s - init; 050 logger.warn("Semaphore: " + x + " pending operations."); 051 } 052 super.finalize(); 053 } 054 055 /** 056 * Performs the P operation. 057 * @throws InterruptedException. 058 */ 059 public synchronized void P() throws InterruptedException { 060 while (s <= 0) { 061 del++; 062 try { this.wait(); 063 } finally { del--; } 064 } 065 s--; 066 } 067 068 /** 069 * Performs the time limited P operation. 070 * @param m time to wait. 071 * @return true if P succeeded, else false. 072 * @throws InterruptedException. 073 */ 074 public synchronized boolean P(int m) throws InterruptedException { 075 if (s <= 0) { 076 del++; 077 try { this.wait(m); 078 } finally { del--; } 079 if (s <= 0) return false; 080 } 081 s--; 082 return true; 083 } 084 085 /** 086 * Performs the V operation. 087 */ 088 public synchronized void V() { 089 s++; 090 if (del > 0) { 091 this.notify(); 092 } 093 } 094 095 /** 096 * Checks if Semaphore is positive. 097 * @return true if Semaphore is positive, else false. 098 */ 099 public boolean isPositive() { 100 return (s > 0); 101 } 102 103 }