KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > javacoding > jspider > core > throttle > impl > DistributedLoadThrottleImpl


1 package net.javacoding.jspider.core.throttle.impl;
2
3
4 import net.javacoding.jspider.core.throttle.Throttle;
5
6
7 /**
8  * Throttle implementation that forces at least x milliseconds between two
9  * subsequent requests on a certain host.
10  *
11  * $Id: DistributedLoadThrottleImpl.java,v 1.2 2003/02/27 16:47:50 vanrogu Exp $
12  *
13  * @author Günther Van Roey
14  */

15 public class DistributedLoadThrottleImpl implements Throttle {
16
17     /** min. milliseconds between two subsequent calls. */
18     protected int milliseconds;
19
20     /** last allowed time for a fetch. */
21     protected long lastAllow;
22
23     /**
24      * Constructor taking the amount of milliseconds to wait between
25      * two subsequent requests as a parameter.
26      * @param milliseconds minimum nr of milliseconds
27      */

28     public DistributedLoadThrottleImpl(int milliseconds) {
29         this.milliseconds = milliseconds;
30         lastAllow = System.currentTimeMillis() - milliseconds;
31     }
32
33     /**
34      * This method will block spider threads until they're allowed
35      * to do a request.
36      */

37     public synchronized void throttle() {
38
39         long thisTime = System.currentTimeMillis();
40         long scheduledTime = lastAllow + milliseconds;
41
42         if (scheduledTime > thisTime) {
43             try {
44                 Thread.sleep(scheduledTime - thisTime);
45             } catch (InterruptedException JavaDoc e) {
46                 Thread.currentThread().interrupt();
47             }
48         }
49
50         lastAllow = System.currentTimeMillis();
51     }
52 }
53
54
Popular Tags