KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibatis > common > util > Throttle


1 /*
2  * Copyright 2004 Clinton Begin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.ibatis.common.util;
17
18 import com.ibatis.common.exception.NestedRuntimeException;
19
20 /**
21  * This is to help keep from getting too many resources
22  */

23 public class Throttle {
24
25   private final Object JavaDoc LOCK = new Object JavaDoc();
26
27   private int count;
28   private int limit;
29   private long maxWait;
30
31   /**
32    * Create a throttle object with just a limit
33    * @param limit - the number of references to allow
34    */

35   public Throttle(int limit) {
36     this.limit = limit;
37     this.maxWait = 0;
38   }
39
40   /**
41    * Create a throttle object with a limit and a wait time
42    * @param limit - the number of references to allow
43    * @param maxWait - the maximum wait time allowed for a reference
44    */

45   public Throttle(int limit, long maxWait) {
46     this.limit = limit;
47     this.maxWait = maxWait;
48   }
49
50   /**
51    * Add a reference; if a reference is not available, an exception is thrown
52    */

53   public void increment() {
54     synchronized (LOCK) {
55       if (count >= limit) {
56         if (maxWait > 0) {
57           long waitTime = System.currentTimeMillis();
58           try {
59             LOCK.wait(maxWait);
60           } catch (InterruptedException JavaDoc e) {
61             //ignore
62
}
63           waitTime = System.currentTimeMillis() - waitTime;
64           if (waitTime > maxWait) {
65             throw new NestedRuntimeException("Throttle waited too long (" + waitTime + ") for lock.");
66           }
67         } else {
68           try {
69             LOCK.wait();
70           } catch (InterruptedException JavaDoc e) {
71             //ignore
72
}
73         }
74       }
75       count++;
76     }
77   }
78
79   /**
80    * Remove a reference
81    */

82   public void decrement() {
83     synchronized (LOCK) {
84       count--;
85       LOCK.notify();
86     }
87   }
88 }
89
Popular Tags