///////////////////////////////////////////////////////// // Module TrafficCop.java // Version 1.00 // Language Java // Author Sudhakar Chandrasekaran (thaths@netscape.com) // History // 05/16/97 Genesis: In the beginning..... // Largely based on 'TrafficController' from the JavaWorld // article about crawlers // // Legalese // Copyright (C) 1996-1997 Sudhakar Chandrasekharan // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the license, or (at your // option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. Writers of free software // cannot afford getting sued! // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 675 Mass Ave., Cambridge, MA 02139, USA. // // Sudhakar "Thaths" Chandrasekharan, 20 April 1997. //////////////////////////////////////////////////////// public class TrafficCop { int tokenDB[]; int currentCrowd; int maximumCrowdSize; // Constructor // Taking the maimum size of a crowd to control, initialize // the crowd to empty and mark all tokens as avialbel public TrafficCop (int max) { maximumCrowdSize = max; currentCrowd = 0; tokenDB = new int [maximumCrowdSize]; for (int i=0; i < maximumCrowdSize; i++) { tokenDB[i] = -1; } } public synchronized int getToken() { while (currentCrowd == maximumCrowdSize) { try { wait(); } catch (InterruptedException imOnlySleeping) { } } int i; for (i=0; i < maximumCrowdSize; i++) { if (tokenDB[i] == -1) { tokenDB[i] = i; currentCrowd++; break; } } return i; } public synchronized void returnToken(int token) { tokenDB[token] = -1; currentCrowd --; notifyAll(); } }