1 package net.javacoding.jspider.core.throttle.impl; 2 3 import net.javacoding.jspider.core.throttle.Throttle; 4 5 import java.util.HashMap ; 6 import java.util.Map ; 7 8 9 22 public class SimultaneousUsersThrottleImpl implements Throttle { 23 24 25 protected Map lastAllows; 26 27 28 protected int min; 29 30 31 protected int max; 32 33 34 39 public SimultaneousUsersThrottleImpl ( int minThinkTime, int maxThinkTime ) { 40 this.min = minThinkTime; 41 this.max = maxThinkTime; 42 this.lastAllows = new HashMap (); 43 } 44 45 49 public void throttle() { 50 Thread thread = Thread.currentThread(); 51 52 Long lastAllowObject = (Long )lastAllows.get(thread); 53 54 if ( lastAllowObject == null ) { 55 lastAllowObject = new Long ( 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 e) { 68 Thread.currentThread().interrupt(); 69 } 70 } 71 lastAllow = System.currentTimeMillis(); 72 lastAllows.put(thread,new Long (lastAllow)); 73 } 74 75 } 76 | Popular Tags |