@@ -2068,30 +2068,63 @@ public Void get() {
20682068 }
20692069
20702070 public static <T > Supplier <T > throttle (final Supplier <T > function , final int waitMilliseconds ) {
2071- class ThrottleFunction implements Supplier <T > {
2071+ class ThrottleLater implements Supplier <T > {
20722072 private final Supplier <T > localFunction ;
2073- private long previous ;
20742073 private java .util .concurrent .ScheduledFuture <T > timeout ;
2074+ private long previous ;
2075+
2076+ ThrottleLater (final Supplier <T > function ) {
2077+ this .localFunction = function ;
2078+ }
2079+
2080+ @ Override
2081+ public T get () {
2082+ previous = now ();
2083+ timeout = null ;
2084+ return localFunction .get ();
2085+ }
2086+
2087+ java .util .concurrent .ScheduledFuture <T > getTimeout () {
2088+ return timeout ;
2089+ }
2090+
2091+ void setTimeout (java .util .concurrent .ScheduledFuture <T > timeout ) {
2092+ this .timeout = timeout ;
2093+ }
2094+
2095+ long getPrevious () {
2096+ return previous ;
2097+ }
2098+
2099+ void setPrevious (long previous ) {
2100+ this .previous = previous ;
2101+ }
2102+ }
2103+
2104+ class ThrottleFunction implements Supplier <T > {
2105+ private final Supplier <T > localFunction ;
2106+ private final ThrottleLater throttleLater ;
20752107
20762108 ThrottleFunction (final Supplier <T > function ) {
20772109 this .localFunction = function ;
2110+ this .throttleLater = new ThrottleLater (function );
20782111 }
20792112
20802113 @ Override
20812114 public T get () {
20822115 final long now = now ();
2083- if (previous == 0L ) {
2084- previous = now ;
2116+ if (throttleLater . getPrevious () == 0L ) {
2117+ throttleLater . setPrevious ( now ) ;
20852118 }
2086- final long remaining = waitMilliseconds - (now - previous );
2119+ final long remaining = waitMilliseconds - (now - throttleLater .getPrevious ());
2120+ T result = null ;
20872121 if (remaining <= 0 ) {
2088- clearTimeout (timeout );
2089- previous = now ;
2090- localFunction .get ();
2091- } else {
2092- timeout = delay (localFunction , waitMilliseconds );
2122+ throttleLater .setPrevious (now );
2123+ result = localFunction .get ();
2124+ } else if (throttleLater .getTimeout () == null ) {
2125+ throttleLater .setTimeout (delay (throttleLater , waitMilliseconds ));
20932126 }
2094- return null ;
2127+ return result ;
20952128 }
20962129 }
20972130 return new ThrottleFunction (function );
0 commit comments