001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.concurrent;
018
019import java.util.concurrent.ScheduledExecutorService;
020import java.util.concurrent.ScheduledFuture;
021import java.util.concurrent.ScheduledThreadPoolExecutor;
022import java.util.concurrent.TimeUnit;
023
024import org.apache.commons.lang3.Validate;
025
026/**
027 * <p>
028 * A specialized <em>semaphore</em> implementation that provides a number of
029 * permits in a given time frame.
030 * </p>
031 * <p>
032 * This class is similar to the {@code java.util.concurrent.Semaphore} class
033 * provided by the JDK in that it manages a configurable number of permits.
034 * Using the {@link #acquire()} method a permit can be requested by a thread.
035 * However, there is an additional timing dimension: there is no {@code
036 * release()} method for freeing a permit, but all permits are automatically
037 * released at the end of a configurable time frame. If a thread calls
038 * {@link #acquire()} and the available permits are already exhausted for this
039 * time frame, the thread is blocked. When the time frame ends all permits
040 * requested so far are restored, and blocking threads are waked up again, so
041 * that they can try to acquire a new permit. This basically means that in the
042 * specified time frame only the given number of operations is possible.
043 * </p>
044 * <p>
045 * A use case for this class is to artificially limit the load produced by a
046 * process. As an example consider an application that issues database queries
047 * on a production system in a background process to gather statistical
048 * information. This background processing should not produce so much database
049 * load that the functionality and the performance of the production system are
050 * impacted. Here a {@code TimedSemaphore} could be installed to guarantee that
051 * only a given number of database queries are issued per second.
052 * </p>
053 * <p>
054 * A thread class for performing database queries could look as follows:
055 * </p>
056 *
057 * <pre>
058 * public class StatisticsThread extends Thread {
059 *     // The semaphore for limiting database load.
060 *     private final TimedSemaphore semaphore;
061 *     // Create an instance and set the semaphore
062 *     public StatisticsThread(TimedSemaphore timedSemaphore) {
063 *         semaphore = timedSemaphore;
064 *     }
065 *     // Gather statistics
066 *     public void run() {
067 *         try {
068 *             while(true) {
069 *                 semaphore.acquire();   // limit database load
070 *                 performQuery();        // issue a query
071 *             }
072 *         } catch(InterruptedException) {
073 *             // fall through
074 *         }
075 *     }
076 *     ...
077 * }
078 * </pre>
079 *
080 * <p>
081 * The following code fragment shows how a {@code TimedSemaphore} is created
082 * that allows only 10 operations per second and passed to the statistics
083 * thread:
084 * </p>
085 *
086 * <pre>
087 * TimedSemaphore sem = new TimedSemaphore(1, TimeUnit.SECOND, 10);
088 * StatisticsThread thread = new StatisticsThread(sem);
089 * thread.start();
090 * </pre>
091 *
092 * <p>
093 * When creating an instance the time period for the semaphore must be
094 * specified. {@code TimedSemaphore} uses an executor service with a
095 * corresponding period to monitor this interval. The {@code
096 * ScheduledExecutorService} to be used for this purpose can be provided at
097 * construction time. Alternatively the class creates an internal executor
098 * service.
099 * </p>
100 * <p>
101 * Client code that uses {@code TimedSemaphore} has to call the
102 * {@link #acquire()} method in aach processing step. {@code TimedSemaphore}
103 * keeps track of the number of invocations of the {@link #acquire()} method and
104 * blocks the calling thread if the counter exceeds the limit specified. When
105 * the timer signals the end of the time period the counter is reset and all
106 * waiting threads are released. Then another cycle can start.
107 * </p>
108 * <p>
109 * It is possible to modify the limit at any time using the
110 * {@link #setLimit(int)} method. This is useful if the load produced by an
111 * operation has to be adapted dynamically. In the example scenario with the
112 * thread collecting statistics it may make sense to specify a low limit during
113 * day time while allowing a higher load in the night time. Reducing the limit
114 * takes effect immediately by blocking incoming callers. If the limit is
115 * increased, waiting threads are not released immediately, but wake up when the
116 * timer runs out. Then, in the next period more processing steps can be
117 * performed without blocking. By setting the limit to 0 the semaphore can be
118 * switched off: in this mode the {@link #acquire()} method never blocks, but
119 * lets all callers pass directly.
120 * </p>
121 * <p>
122 * When the {@code TimedSemaphore} is no more needed its {@link #shutdown()}
123 * method should be called. This causes the periodic task that monitors the time
124 * interval to be canceled. If the {@code ScheduledExecutorService} has been
125 * created by the semaphore at construction time, it is also shut down.
126 * resources. After that {@link #acquire()} must not be called any more.
127 * </p>
128 *
129 * @since 3.0
130 */
131public class TimedSemaphore {
132    /**
133     * Constant for a value representing no limit. If the limit is set to a
134     * value less or equal this constant, the {@code TimedSemaphore} will be
135     * effectively switched off.
136     */
137    public static final int NO_LIMIT = 0;
138
139    /** Constant for the thread pool size for the executor. */
140    private static final int THREAD_POOL_SIZE = 1;
141
142    /** The executor service for managing the timer thread. */
143    private final ScheduledExecutorService executorService;
144
145    /** Stores the period for this timed semaphore. */
146    private final long period;
147
148    /** The time unit for the period. */
149    private final TimeUnit unit;
150
151    /** A flag whether the executor service was created by this object. */
152    private final boolean ownExecutor;
153
154    /** A future object representing the timer task. */
155    private ScheduledFuture<?> task; // @GuardedBy("this")
156
157    /** Stores the total number of invocations of the acquire() method. */
158    private long totalAcquireCount; // @GuardedBy("this")
159
160    /**
161     * The counter for the periods. This counter is increased every time a
162     * period ends.
163     */
164    private long periodCount; // @GuardedBy("this")
165
166    /** The limit. */
167    private int limit; // @GuardedBy("this")
168
169    /** The current counter. */
170    private int acquireCount;  // @GuardedBy("this")
171
172    /** The number of invocations of acquire() in the last period. */
173    private int lastCallsPerPeriod; // @GuardedBy("this")
174
175    /** A flag whether shutdown() was called. */
176    private boolean shutdown;  // @GuardedBy("this")
177
178    /**
179     * Creates a new instance of {@link TimedSemaphore} and initializes it with
180     * the given time period and the limit.
181     *
182     * @param timePeriod the time period
183     * @param timeUnit the unit for the period
184     * @param limit the limit for the semaphore
185     * @throws IllegalArgumentException if the period is less or equals 0
186     */
187    public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit) {
188        this(null, timePeriod, timeUnit, limit);
189    }
190
191    /**
192     * Creates a new instance of {@link TimedSemaphore} and initializes it with
193     * an executor service, the given time period, and the limit. The executor
194     * service will be used for creating a periodic task for monitoring the time
195     * period. It can be <b>null</b>, then a default service will be created.
196     *
197     * @param service the executor service
198     * @param timePeriod the time period
199     * @param timeUnit the unit for the period
200     * @param limit the limit for the semaphore
201     * @throws IllegalArgumentException if the period is less or equals 0
202     */
203    public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod,
204            final TimeUnit timeUnit, final int limit) {
205        Validate.inclusiveBetween(1, Long.MAX_VALUE, timePeriod, "Time period must be greater than 0!");
206
207        period = timePeriod;
208        unit = timeUnit;
209
210        if (service != null) {
211            executorService = service;
212            ownExecutor = false;
213        } else {
214            final ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(
215                    THREAD_POOL_SIZE);
216            s.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
217            s.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
218            executorService = s;
219            ownExecutor = true;
220        }
221
222        setLimit(limit);
223    }
224
225    /**
226     * Returns the limit enforced by this semaphore. The limit determines how
227     * many invocations of {@link #acquire()} are allowed within the monitored
228     * period.
229     *
230     * @return the limit
231     */
232    public final synchronized int getLimit() {
233        return limit;
234    }
235
236    /**
237     * Sets the limit. This is the number of times the {@link #acquire()} method
238     * can be called within the time period specified. If this limit is reached,
239     * further invocations of {@link #acquire()} will block. Setting the limit
240     * to a value &lt;= {@link #NO_LIMIT} will cause the limit to be disabled,
241     * i.e. an arbitrary number of{@link #acquire()} invocations is allowed in
242     * the time period.
243     *
244     * @param limit the limit
245     */
246    public final synchronized void setLimit(final int limit) {
247        this.limit = limit;
248    }
249
250    /**
251     * Initializes a shutdown. After that the object cannot be used any more.
252     * This method can be invoked an arbitrary number of times. All invocations
253     * after the first one do not have any effect.
254     */
255    public synchronized void shutdown() {
256        if (!shutdown) {
257
258            if (ownExecutor) {
259                // if the executor was created by this instance, it has
260                // to be shutdown
261                getExecutorService().shutdownNow();
262            }
263            if (task != null) {
264                task.cancel(false);
265            }
266
267            shutdown = true;
268        }
269    }
270
271    /**
272     * Tests whether the {@link #shutdown()} method has been called on this
273     * object. If this method returns <b>true</b>, this instance cannot be used
274     * any longer.
275     *
276     * @return a flag whether a shutdown has been performed
277     */
278    public synchronized boolean isShutdown() {
279        return shutdown;
280    }
281
282    /**
283     * Tries to acquire a permit from this semaphore. This method will block if
284     * the limit for the current period has already been reached. If
285     * {@link #shutdown()} has already been invoked, calling this method will
286     * cause an exception. The very first call of this method starts the timer
287     * task which monitors the time period set for this {@code TimedSemaphore}.
288     * From now on the semaphore is active.
289     *
290     * @throws InterruptedException if the thread gets interrupted
291     * @throws IllegalStateException if this semaphore is already shut down
292     */
293    public synchronized void acquire() throws InterruptedException {
294        if (isShutdown()) {
295            throw new IllegalStateException("TimedSemaphore is shut down!");
296        }
297
298        if (task == null) {
299            task = startTimer();
300        }
301
302        boolean canPass = false;
303        do {
304            canPass = getLimit() <= NO_LIMIT || acquireCount < getLimit();
305            if (!canPass) {
306                wait();
307            } else {
308                acquireCount++;
309            }
310        } while (!canPass);
311    }
312
313    /**
314     * Returns the number of (successful) acquire invocations during the last
315     * period. This is the number of times the {@link #acquire()} method was
316     * called without blocking. This can be useful for testing or debugging
317     * purposes or to determine a meaningful threshold value. If a limit is set,
318     * the value returned by this method won't be greater than this limit.
319     *
320     * @return the number of non-blocking invocations of the {@link #acquire()}
321     * method
322     */
323    public synchronized int getLastAcquiresPerPeriod() {
324        return lastCallsPerPeriod;
325    }
326
327    /**
328     * Returns the number of invocations of the {@link #acquire()} method for
329     * the current period. This may be useful for testing or debugging purposes.
330     *
331     * @return the current number of {@link #acquire()} invocations
332     */
333    public synchronized int getAcquireCount() {
334        return acquireCount;
335    }
336
337    /**
338     * Returns the number of calls to the {@link #acquire()} method that can
339     * still be performed in the current period without blocking. This method
340     * can give an indication whether it is safe to call the {@link #acquire()}
341     * method without risking to be suspended. However, there is no guarantee
342     * that a subsequent call to {@link #acquire()} actually is not-blocking
343     * because in the mean time other threads may have invoked the semaphore.
344     *
345     * @return the current number of available {@link #acquire()} calls in the
346     * current period
347     */
348    public synchronized int getAvailablePermits() {
349        return getLimit() - getAcquireCount();
350    }
351
352    /**
353     * Returns the average number of successful (i.e. non-blocking)
354     * {@link #acquire()} invocations for the entire life-time of this {@code
355     * TimedSemaphore}. This method can be used for instance for statistical
356     * calculations.
357     *
358     * @return the average number of {@link #acquire()} invocations per time
359     * unit
360     */
361    public synchronized double getAverageCallsPerPeriod() {
362        return periodCount == 0 ? 0 : (double) totalAcquireCount
363                / (double) periodCount;
364    }
365
366    /**
367     * Returns the time period. This is the time monitored by this semaphore.
368     * Only a given number of invocations of the {@link #acquire()} method is
369     * possible in this period.
370     *
371     * @return the time period
372     */
373    public long getPeriod() {
374        return period;
375    }
376
377    /**
378     * Returns the time unit. This is the unit used by {@link #getPeriod()}.
379     *
380     * @return the time unit
381     */
382    public TimeUnit getUnit() {
383        return unit;
384    }
385
386    /**
387     * Returns the executor service used by this instance.
388     *
389     * @return the executor service
390     */
391    protected ScheduledExecutorService getExecutorService() {
392        return executorService;
393    }
394
395    /**
396     * Starts the timer. This method is called when {@link #acquire()} is called
397     * for the first time. It schedules a task to be executed at fixed rate to
398     * monitor the time period specified.
399     *
400     * @return a future object representing the task scheduled
401     */
402    protected ScheduledFuture<?> startTimer() {
403        return getExecutorService().scheduleAtFixedRate(new Runnable() {
404            @Override
405            public void run() {
406                endOfPeriod();
407            }
408        }, getPeriod(), getPeriod(), getUnit());
409    }
410
411    /**
412     * The current time period is finished. This method is called by the timer
413     * used internally to monitor the time period. It resets the counter and
414     * releases the threads waiting for this barrier.
415     */
416    synchronized void endOfPeriod() {
417        lastCallsPerPeriod = acquireCount;
418        totalAcquireCount += acquireCount;
419        periodCount++;
420        acquireCount = 0;
421        notifyAll();
422    }
423}