SimultaneousUsersThrottleImpl.java
上传用户:qing5858
上传日期:2015-10-27
资源大小:6056k
文件大小:2k
源码类别:

搜索引擎

开发平台:

Java

  1. package net.javacoding.jspider.core.throttle.impl;
  2. import net.javacoding.jspider.core.throttle.Throttle;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. /**
  6.  * Throttle implementation that displays behaviour like multiple simultaneous
  7.  * users would do.  Each worker thread (which represents a user) is throttled
  8.  * separately, and the latency between two requests is a random value between
  9.  * a configurable minimum and maximum value.
  10.  * This way, a normal web user's 'thinking time' can be faked.  More inequal
  11.  * partitioning of requests on the webserver will be the result, as with
  12.  * human users accessing a system.
  13.  *
  14.  * $Id: SimultaneousUsersThrottleImpl.java,v 1.3 2003/02/27 16:47:51 vanrogu Exp $
  15.  *
  16.  * @author  G黱ther Van Roey
  17.  */
  18. public class SimultaneousUsersThrottleImpl implements Throttle {
  19.     /** Map which contains the last fetch times per worker thread (user). */
  20.     protected Map lastAllows;
  21.     /** configured minimum value of thinking time. */
  22.     protected int min;
  23.     /** configured maximum value of thinking time. */
  24.     protected int max;
  25.     /**
  26.      * Public constructor taking the thinking time min and max values as params.
  27.      * @param minThinkTime the minimum time between two requests from the same user
  28.      * @param maxThinkTime the maximum time between two requests from the same user
  29.      */
  30.     public SimultaneousUsersThrottleImpl ( int minThinkTime, int maxThinkTime ) {
  31.         this.min = minThinkTime;
  32.         this.max = maxThinkTime;
  33.         this.lastAllows = new HashMap();
  34.     }
  35.     /**
  36.      * Implemented throttle method of the Throttle interface, which will keep
  37.      * the worker threads under control.
  38.      */
  39.     public void throttle() {
  40.         Thread thread = Thread.currentThread();
  41.         Long lastAllowObject = (Long)lastAllows.get(thread);
  42.         if ( lastAllowObject == null ) {
  43.             lastAllowObject = new Long ( System.currentTimeMillis() );
  44.         }
  45.         long lastAllow = lastAllowObject.longValue();
  46.         long thisTime = System.currentTimeMillis();
  47.         long milliseconds = min + (int)(Math.random() * ( max-min ) );
  48.         long scheduledTime = lastAllow + milliseconds;
  49.         if (scheduledTime > thisTime) {
  50.             try {
  51.                 Thread.sleep(scheduledTime - thisTime);
  52.             } catch (InterruptedException e) {
  53.                 Thread.currentThread().interrupt();
  54.             }
  55.         }
  56.         lastAllow = System.currentTimeMillis();
  57.         lastAllows.put(thread,new Long(lastAllow));
  58.     }
  59. }