01: /*
02: * Copyright 2001 Sun Microsystems, Inc. All rights reserved.
03: * PROPRIETARY/CONFIDENTIAL. Use of this product is subject to license terms.
04: */
05:
06: package com.sun.portal.search.util;
07:
08: /**
09: * N-way counting semaphore.
10: */
11: public class Semaphore {
12:
13: private int value = 0;
14: private int waitCount = 0;
15: private int notifyCount = 0;
16:
17: /**
18: * Create a semaphore of size n.
19: * Allow up to n outstanding acquisitions.
20: */
21: public Semaphore(int n) {
22: if (n < 0)
23: throw new IllegalArgumentException();
24: value = n;
25: }
26:
27: /**
28: * Acquire the semaphore. Waits until count is > 0.
29: * @exception InterruptedException
30: */
31: public synchronized void acquire() throws InterruptedException {
32: if (value <= waitCount) {
33: waitCount++;
34: try {
35: do {
36: wait();
37: } while (notifyCount == 0);
38: } catch (InterruptedException e) {
39: notify();
40: throw e;
41: } finally {
42: waitCount--;
43: }
44: notifyCount--;
45: }
46: value--;
47: }
48:
49: /**
50: * Release the semaphore.
51: */
52: public synchronized void release() {
53: value++;
54: if (waitCount > notifyCount) {
55: notifyCount++;
56: notify();
57: }
58: }
59:
60: }
|