01: // ***************************************************************
02: // * *
03: // * File: Semaphore.java *
04: // * *
05: // * Copyright (c) 2001 Sun Microsystems, Inc. *
06: // * All rights reserved. *
07: // * *
08: // * *
09: // * Date - Dec/11/2001 *
10: // * Author - alejandro.abdelnur@sun.com *
11: // * *
12: // ***************************************************************
13:
14: package com.sun.portal.common.concurrent;
15:
16: /**
17: * Semaphore provides synchronized access to shared objects.
18: *
19: */
20: public class Semaphore {
21: private int _maxConcurrentUsers;
22: private int _currentUsers;
23: private ConsumerProducer _queue;
24:
25: /**
26: *
27: * @param maxConcurrentUsers if 0 means no restrictions on
28: * number of concurrent users.
29: *
30: */
31: public Semaphore(int maxConcurrentUsers) {
32: if (maxConcurrentUsers < 0) {
33: throw new IllegalArgumentException(
34: "Semaphore <init> - maxConcurrentUsers has to be 0 or greater");
35: }
36: _maxConcurrentUsers = maxConcurrentUsers;
37: _currentUsers = 0;
38: }
39:
40: /**
41: * Returns the maximum number of concurrent users
42: *
43: * @return the maximum number of concurrent users
44: *
45: */
46: public int getMaxConcurrentUsers() {
47: return _maxConcurrentUsers;
48: }
49:
50: /**
51: * Returns the current number of concurrent users
52: *
53: * @return the current number of concurrent users
54: *
55: */
56: public int getCurrentUsers() {
57: return _currentUsers;
58: }
59:
60: /**
61: * Using sWait as wait is an Object method.
62: *
63: */
64: public void sWait() throws InterruptedException {
65: if (_maxConcurrentUsers > 0) {
66: boolean go;
67: synchronized (this ) {
68: _currentUsers++;
69: if (_currentUsers > _maxConcurrentUsers) {
70: wait();
71: }
72: }
73: }
74: }
75:
76: /**
77: * Using sSignal for consistency with sWait.
78: *
79: */
80: public void sSignal() {
81: if (_maxConcurrentUsers > 0) {
82: synchronized (this ) {
83: if (_currentUsers > 0) {
84: _currentUsers--;
85: }
86: notify();
87: }
88: }
89: }
90:
91: }
|