KickJava   Java API By Example, From Geeks To Geeks.

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


1 package net.javacoding.jspider.core.throttle.impl;
2
3 import net.javacoding.jspider.core.throttle.Throttle;
4
5 import java.util.HashMap JavaDoc;
6 import java.util.Map JavaDoc;
7
8
9 /**
10  * Throttle implementation that displays behaviour like multiple simultaneous
11  * users would do. Each worker thread (which represents a user) is throttled
12  * separately, and the latency between two requests is a random value between
13  * a configurable minimum and maximum value.
14  * This way, a normal web user's 'thinking time' can be faked. More inequal
15  * partitioning of requests on the webserver will be the result, as with
16  * human users accessing a system.
17  *
18  * $Id: SimultaneousUsersThrottleImpl.java,v 1.3 2003/02/27 16:47:51 vanrogu Exp $
19  *
20  * @author Günther Van Roey
21  */

22 public class SimultaneousUsersThrottleImpl implements Throttle {
23
24     /** Map which contains the last fetch times per worker thread (user). */
25     protected Map JavaDoc lastAllows;
26
27     /** configured minimum value of thinking time. */
28     protected int min;
29
30     /** configured maximum value of thinking time. */
31     protected int max;
32
33
34     /**
35      * Public constructor taking the thinking time min and max values as params.
36      * @param minThinkTime the minimum time between two requests from the same user
37      * @param maxThinkTime the maximum time between two requests from the same user
38      */

39     public SimultaneousUsersThrottleImpl ( int minThinkTime, int maxThinkTime ) {
40         this.min = minThinkTime;
41         this.max = maxThinkTime;
42         this.lastAllows = new HashMap JavaDoc();
43     }
44
45     /**
46      * Implemented throttle method of the Throttle interface, which will keep
47      * the worker threads under control.
48      */

49     public void throttle() {
50         Thread JavaDoc thread = Thread.currentThread();
51
52         Long JavaDoc lastAllowObject = (Long JavaDoc)lastAllows.get(thread);
53
54         if ( lastAllowObject == null ) {
55             lastAllowObject = new Long JavaDoc ( System.currentTimeMillis() );
56         }
57
58         long lastAllow = lastAllowObject.longValue();
59         long thisTime = System.currentTimeMillis();
60         long milliseconds = min + (int)(Math.random() * ( max-min ) );
61
62         long scheduledTime = lastAllow + milliseconds;
63
64         if (scheduledTime > thisTime) {
65             try {
66                 Thread.sleep(scheduledTime - thisTime);
67             } catch (InterruptedException JavaDoc e) {
68                 Thread.currentThread().interrupt();
69             }
70         }
71         lastAllow = System.currentTimeMillis();
72         lastAllows.put(thread,new Long JavaDoc(lastAllow));
73     }
74
75 }
76
Popular Tags