001    /*
002     * Copyright 2009-2014 UnboundID Corp.
003     * All Rights Reserved.
004     */
005    /*
006     * Copyright (C) 2009-2014 UnboundID Corp.
007     *
008     * This program is free software; you can redistribute it and/or modify
009     * it under the terms of the GNU General Public License (GPLv2 only)
010     * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
011     * as published by the Free Software Foundation.
012     *
013     * This program is distributed in the hope that it will be useful,
014     * but WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     * GNU General Public License for more details.
017     *
018     * You should have received a copy of the GNU General Public License
019     * along with this program; if not, see <http://www.gnu.org/licenses>.
020     */
021    package com.unboundid.util;
022    
023    
024    
025    import java.io.Serializable;
026    import java.util.ArrayList;
027    import java.util.Collections;
028    import java.util.List;
029    import java.util.logging.Level;
030    
031    import static com.unboundid.util.Debug.*;
032    
033    
034    
035    /**
036     * Instances of this class are used to ensure that certain actions are performed
037     * at a fixed rate per interval (e.g. 10000 search operations per second).
038     * <p>
039     * Once a class is constructed with the duration of an interval and the target
040     * per interval, the {@link #await} method only releases callers at the
041     * specified number of times per interval.  This class is most useful when
042     * the target number per interval exceeds the limits of other approaches
043     * such as {@code java.util.Timer} or
044     * {@code java.util.concurrent.ScheduledThreadPoolExecutor}.  For instance,
045     * this does a good job of ensuring that something happens about 10000 times
046     * per second, but it's overkill to ensure something happens five times per
047     * hour.  This does come at a cost.  In the worst case, a single thread is
048     * tied up in a loop doing a small amount of computation followed by a
049     * Thread.yield().  Calling Thread.sleep() is not possible because many
050     * platforms sleep for a minimum of 10ms, and all platforms require sleeping
051     * for at least 1ms.
052     * <p>
053     * Testing has shown that this class is accurate for a "no-op"
054     * action up to two million per second, which vastly exceeds its
055     * typical use in tools such as {@code searchrate} and {@code modrate}.  This
056     * class is designed to be called by multiple threads, however, it does not
057     * make any fairness guarantee between threads; a single-thread might be
058     * released from the {@link #await} method many times before another thread
059     * that is blocked in that method.
060     * <p>
061     * This class attempts to smooth out the target per interval throughout each
062     * interval.  At a given ratio, R between 0 and 1, through the interval, the
063     * expected number of actions to have been performed in the interval at that
064     * time is R times the target per interval.  That is, 10% of the way through
065     * the interval, approximately 10% of the actions have been performed, and
066     * 80% of the way through the interval, 80% of the actions have been performed.
067     */
068    @ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
069    public final class FixedRateBarrier
070           implements Serializable
071    {
072      /**
073       * The serial version UID for this serializable class.
074       */
075      private static final long serialVersionUID = -3490156685189909611L;
076    
077      /**
078       * The minimum number of milliseconds that Thread.sleep() can handle
079       * accurately.  This varies from platform to platform, so we measure it
080       * once in the static initializer below.  When using a low rate (such as
081       * 100 per second), we can often sleep between iterations instead of having
082       * to spin calling Thread.yield().
083       */
084      private static final long minSleepMillis;
085    
086      static
087      {
088        // Calibrate the minimum number of milliseconds that we can reliably
089        // sleep on this system.  We take several measurements and take the median,
090        // which keeps us from choosing an outlier.
091        //
092        // It varies from system to system.  Testing on three systems, yielded
093        // three different measurements Solaris x86 (10 ms), RedHat Linux (2 ms),
094        // Windows 7 (1 ms).
095    
096        final List<Long> minSleepMillisMeasurements = new ArrayList<Long>();
097    
098        for (int i = 0; i < 11; i++)
099        {
100          final long timeBefore = System.currentTimeMillis();
101          try
102          {
103            Thread.sleep(1);
104          }
105          catch (InterruptedException e)
106          {
107            debugException(e);
108          }
109          final long sleepMillis = System.currentTimeMillis() - timeBefore;
110          minSleepMillisMeasurements.add(sleepMillis);
111        }
112    
113        Collections.sort(minSleepMillisMeasurements);
114        final long medianSleepMillis = minSleepMillisMeasurements.get(
115                minSleepMillisMeasurements.size()/2);
116    
117        minSleepMillis = Math.max(medianSleepMillis, 1);
118    
119        final String message = "Calibrated FixedRateBarrier to use " +
120              "minSleepMillis=" + minSleepMillis + ".  " +
121              "Minimum sleep measurements = " + minSleepMillisMeasurements;
122        debug(Level.INFO, DebugType.OTHER, message);
123      }
124    
125    
126      // The duration of the target interval in nano-seconds.
127      private final long intervalDurationNanos;
128    
129      // This tracks the number of milliseconds between each iteration if they
130      // were evenly spaced.
131      //
132      // If intervalDurationMs=1000 and perInterval=100, then this is 100.
133      // If intervalDurationMs=1000 and perInterval=10000, then this is .1.
134      private final double millisBetweenIterations;
135    
136      // The target number of times to release a thread per interval.
137      private final int perInterval;
138    
139      // This tracks when this class is shutdown.  Calls to await() after
140      // shutdownRequested() is called, will return immediately with a value of
141      // true.
142      private volatile boolean shutdownRequested = false;
143    
144      //
145      // The following class variables are guarded by synchronized(this).
146      //
147    
148      // A count of the number of times that await has returned within the current
149      // interval.
150      private long countInThisInterval = 0;
151    
152      // The start of this interval in terms of System.nanoTime().
153      private long intervalStartNanos = 0;
154    
155      // The end of this interval in terms of System.nanoTime().
156      private long intervalEndNanos = 0;
157    
158    
159    
160      /**
161       * Constructs a new FixedRateBarrier, which is active until
162       * {@link #shutdownRequested} is called.
163       *
164       * @param  intervalDurationMs  The duration of the interval in milliseconds.
165       * @param  perInterval  The target number of times that {@link #await} should
166       *                      return per interval.
167       */
168      public FixedRateBarrier(final long intervalDurationMs, final int perInterval)
169      {
170        Validator.ensureTrue(intervalDurationMs > 0,
171             "FixedRateBarrier.intervalDurationMs must be at least 1.");
172        Validator.ensureTrue(perInterval > 0,
173             "FixedRateBarrier.perInterval must be at least 1.");
174    
175        this.perInterval = perInterval;
176    
177        intervalDurationNanos = 1000L * 1000L * intervalDurationMs;
178    
179        millisBetweenIterations = (double)intervalDurationMs/(double)perInterval;
180      }
181    
182    
183    
184      /**
185       * This method waits until it is time for the next 'action' to be performed
186       * based on the specified interval duration and target per interval.  This
187       * method can be called by multiple threads simultaneously.  This method
188       * returns immediately if shutdown has been requested.
189       *
190       * @return  {@code true} if shutdown has been requested and {@code} false
191       *          otherwise.
192       */
193      public synchronized boolean await()
194      {
195        // Loop forever until we are requested to shutdown or it is time to perform
196        // the next 'action' in which case we break from the loop.
197        while (!shutdownRequested)
198        {
199          final long now = System.nanoTime();
200    
201          if ((intervalStartNanos == 0) ||   // Handles the first time we're called.
202              (now < intervalStartNanos))    // Handles a change in the clock.
203          {
204            intervalStartNanos = now;
205            intervalEndNanos = intervalStartNanos + intervalDurationNanos;
206          }
207          else if (now >= intervalEndNanos)  // End of an interval.
208          {
209            countInThisInterval = 0;
210    
211            if (now < (intervalEndNanos + intervalDurationNanos))
212            {
213              // If we have already passed the end of the next interval, then we
214              // don't try to catch up.  Instead we just reset the start of the
215              // next interval to now.  This could happen if the system clock
216              // was set to the future, we're running in a debugger, or we have
217              // very short intervals and are unable to keep up.
218              intervalStartNanos = now;
219            }
220            else
221            {
222              // Usually we're some small fraction into the next interval, so
223              // we set the start of the current interval to the end of the
224              // previous one.
225              intervalStartNanos = intervalEndNanos;
226            }
227            intervalEndNanos = intervalStartNanos + intervalDurationNanos;
228          }
229    
230          final long intervalRemaining = intervalEndNanos - now;
231          if (intervalRemaining <= 0)
232          {
233            // This shouldn't happen, but we're careful not to divide by 0.
234            continue;
235          }
236    
237          final double intervalFractionRemaining =
238               (double) intervalRemaining / intervalDurationNanos;
239    
240          final double expectedRemaining = intervalFractionRemaining * perInterval;
241          final long actualRemaining = perInterval - countInThisInterval;
242    
243          if (actualRemaining >= expectedRemaining)
244          {
245            // We are on schedule or behind schedule so let the next 'action'
246            // happen.
247            countInThisInterval++;
248            break;
249          }
250          else
251          {
252            // If we can sleep until it's time to leave this barrier, then do
253            // so to keep from spinning on a CPU doing Thread.yield().
254    
255            final double gapIterations = expectedRemaining - actualRemaining;
256            final double remainingMillis =
257                    millisBetweenIterations * gapIterations;
258    
259            if (remainingMillis >= minSleepMillis)
260            {
261              try
262              {
263                Thread.sleep((long)remainingMillis);
264              }
265              catch (InterruptedException e)
266              {
267                debugException(e);
268              }
269            }
270            else
271            {
272              // We're ahead of schedule so yield to other threads, and then try
273              // again.  Note: this is the most costly part of the algorithm because
274              // we have to busy wait due to the lack of sleeping for very small
275              // amounts of time.
276              Thread.yield();
277            }
278          }
279        }
280    
281        return shutdownRequested;
282      }
283    
284    
285    
286      /**
287       * Shuts down this barrier.  Future calls to await() will return immediately.
288       */
289      public void shutdownRequested()
290      {
291        shutdownRequested = true;
292      }
293    
294    
295    
296      /**
297       * Returns {@code true} if shutdown has been requested.
298       *
299       * @return  {@code true} if shutdown has been requested and {@code false}
300       *          otherwise.
301       */
302      public boolean isShutdownRequested()
303      {
304        return shutdownRequested;
305      }
306    }