Top Description Inners Fields Constructors Methods
org.apache.commons.lang3.concurrent

public Class TimedSemaphore

extends Object
Class Inheritance
Imports
java.util.concurrent.ScheduledExecutorService, .ScheduledFuture, .ScheduledThreadPoolExecutor, .TimeUnit, java.util.function.Supplier, org.apache.commons.lang3.Validate

A specialized semaphore implementation that provides a number of permits in a given time frame.

This class is similar to the java.util.concurrent.Semaphore class provided by the JDK in that it manages a configurable number of permits. Using the acquire() method a permit can be requested by a thread. However, there is an additional timing dimension: there is no release() method for freeing a permit, but all permits are automatically released at the end of a configurable time frame. If a thread calls acquire() and the available permits are already exhausted for this time frame, the thread is blocked. When the time frame ends all permits requested so far are restored, and blocking threads are waked up again, so that they can try to acquire a new permit. This basically means that in the specified time frame only the given number of operations is possible.

A use case for this class is to artificially limit the load produced by a process. As an example consider an application that issues database queries on a production system in a background process to gather statistical information. This background processing should not produce so much database load that the functionality and the performance of the production system are impacted. Here a TimedSemaphore could be installed to guarantee that only a given number of database queries are issued per second.

A thread class for performing database queries could look as follows:

public class StatisticsThread extends Thread {
    // The semaphore for limiting database load.
    private final TimedSemaphore semaphore;
    // Create an instance and set the semaphore
    public StatisticsThread(TimedSemaphore timedSemaphore) {
        semaphore = timedSemaphore;
    }
    // Gather statistics
    public void run() {
        try {
            while (true) {
                semaphore.acquire();   // limit database load
                performQuery();        // issue a query
            }
        } catch (InterruptedException) {
            // fall through
        }
    }
    ...
}

The following code fragment shows how a TimedSemaphore is created that allows only 10 operations per second and passed to the statistics thread:

TimedSemaphore sem = new TimedSemaphore(1, TimeUnit.SECOND, 10);
StatisticsThread thread = new StatisticsThread(sem);
thread.start();

When creating an instance the time period for the semaphore must be specified. TimedSemaphore uses an executor service with a corresponding period to monitor this interval. The ScheduledExecutorService to be used for this purpose can be provided at construction time. Alternatively the class creates an internal executor service.

Client code that uses TimedSemaphore has to call the acquire() method in each processing step. TimedSemaphore keeps track of the number of invocations of the acquire() method and blocks the calling thread if the counter exceeds the limit specified. When the timer signals the end of the time period the counter is reset and all waiting threads are released. Then another cycle can start.

An alternative to acquire() is the tryAcquire() method. This method checks whether the semaphore is under the specified limit and increases the internal counter if this is the case. The return value is then true, and the calling thread can continue with its action. If the semaphore is already at its limit, tryAcquire() immediately returns false without blocking; the calling thread must then abort its action. This usage scenario prevents blocking of threads.

It is possible to modify the limit at any time using the setLimit(int) method. This is useful if the load produced by an operation has to be adapted dynamically. In the example scenario with the thread collecting statistics it may make sense to specify a low limit during day time while allowing a higher load in the night time. Reducing the limit takes effect immediately by blocking incoming callers. If the limit is increased, waiting threads are not released immediately, but wake up when the timer runs out. Then, in the next period more processing steps can be performed without blocking. By setting the limit to 0 the semaphore can be switched off: in this mode the acquire() method never blocks, but lets all callers pass directly.

When the TimedSemaphore is no more needed its shutdown() method should be called. This causes the periodic task that monitors the time interval to be canceled. If the ScheduledExecutorService has been created by the semaphore at construction time, it is also shut down. resources. After that acquire() must not be called any more.

Since
3.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class

Field Summary

Modifier and TypeField and Description
private int
acquireCount

The current counter.

private final ScheduledExecutorService
executorService

The executor service for managing the timer thread.

private int
lastCallsPerPeriod

The number of invocations of acquire() in the last period.

private int
limit

The limit.

public static final int
NO_LIMIT

Constant for a value representing no limit.

private final boolean
ownExecutor

A flag whether the executor service was created by this object.

private final long
period

The period for this timed semaphore.

private long
periodCount

The counter for the periods.

private boolean
shutdown

A flag whether shutdown() was called.

private ScheduledFuture<?>
task

A future object representing the timer task.

private static final int
THREAD_POOL_SIZE

Constant for the thread pool size for the executor.

private long
totalAcquireCount

Stores the total number of invocations of the acquire() method.

private final TimeUnit
unit

The time unit for the period.

Constructor Summary

AccessConstructor and Description
private
public
TimedSemaphore(final long
the time period.
timePeriod
,
final TimeUnit
the unit for the period.
timeUnit
,
final int
the limit for the semaphore.
limit
)
Deprecated Use builder() and Builder.

Constructs a new instance of TimedSemaphore and initializes it with the given time period and the limit.

public
TimedSemaphore(final ScheduledExecutorService
the executor service.
service
,
final long
the time period.
timePeriod
,
final TimeUnit
the unit for the period.
timeUnit
,
final int
the limit for the semaphore.
limit
)
Deprecated Use builder() and Builder.

Constructs a new instance of TimedSemaphore and initializes it with an executor service, the given time period, and the limit.

Method Summary

Modifier and TypeMethod and Description
public synchronized void
acquire()

Acquires a permit from this semaphore.

private boolean

Returns:

a flag whether a permit could be acquired.
acquirePermit
()

Internal helper method for acquiring a permit.

public static TimedSemaphore.Builder

Returns:

a new Builder.
builder
()

Constructs a new Builder.

pack-priv synchronized void
endOfPeriod()

The current time period is finished.

public synchronized int

Returns:

the current number of acquire() invocations.
getAcquireCount
()

Gets the number of invocations of the acquire() method for the current period.

public synchronized int

Returns:

the current number of available acquire() calls in the current period.
getAvailablePermits
()

Gets the number of calls to the acquire() method that can still be performed in the current period without blocking.

public synchronized double

Returns:

the average number of acquire() invocations per time unit.
getAverageCallsPerPeriod
()

Gets the average number of successful (i.e. non-blocking) acquire() invocations for the entire life-time of this TimedSemaphore.

protected ScheduledExecutorService

Returns:

the executor service.
getExecutorService
()

Gets the executor service used by this instance.

public synchronized int

Returns:

the number of non-blocking invocations of the acquire() method.
getLastAcquiresPerPeriod
()

Gets the number of (successful) acquire invocations during the last period.

public final synchronized int

Returns:

the limit.
getLimit
()

Gets the limit enforced by this semaphore.

public long

Returns:

the time period.
getPeriod
()

Gets the time period.

public TimeUnit

Returns:

the time unit.
getUnit
()

Gets the time unit.

public synchronized boolean

Returns:

a flag whether a shutdown has been performed.
isShutdown
()

Tests whether the shutdown() method has been called on this object.

private void
prepareAcquire()

Prepares an acquire operation.

public final synchronized void
setLimit(final int
the limit.
limit
)

Sets the limit.

public synchronized void
shutdown()

Initializes a shutdown.

protected ScheduledFuture<?>

Returns:

a future object representing the task scheduled.
startTimer
()

Starts the timer.

public synchronized boolean

Returns:

true if a permit could be acquired; false otherwise.
tryAcquire
()

Tries to acquire a permit from this semaphore.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

acquireCountback to summary
private int acquireCount

The current counter.

executorServiceback to summary
private final ScheduledExecutorService executorService

The executor service for managing the timer thread.

lastCallsPerPeriodback to summary
private int lastCallsPerPeriod

The number of invocations of acquire() in the last period.

limitback to summary
private int limit

The limit.

NO_LIMITback to summary
public static final int NO_LIMIT

Constant for a value representing no limit. If the limit is set to a value less or equal this constant, the TimedSemaphore will be effectively switched off.

ownExecutorback to summary
private final boolean ownExecutor

A flag whether the executor service was created by this object.

periodback to summary
private final long period

The period for this timed semaphore.

periodCountback to summary
private long periodCount

The counter for the periods. This counter is increased every time a period ends.

shutdownback to summary
private boolean shutdown

A flag whether shutdown() was called.

taskback to summary
private ScheduledFuture<?> task

A future object representing the timer task.

THREAD_POOL_SIZEback to summary
private static final int THREAD_POOL_SIZE

Constant for the thread pool size for the executor.

totalAcquireCountback to summary
private long totalAcquireCount

Stores the total number of invocations of the acquire() method.

unitback to summary
private final TimeUnit unit

The time unit for the period.

Constructor Detail

TimedSemaphoreback to summary
private TimedSemaphore(final TimedSemaphore.Builder builder)
TimedSemaphoreback to summary
public TimedSemaphore(final long timePeriod, final TimeUnit timeUnit, final int limit)

Deprecated

Use builder() and Builder.

Constructs a new instance of TimedSemaphore and initializes it with the given time period and the limit.

Parameters
timePeriod:long

the time period.

timeUnit:TimeUnit

the unit for the period.

limit:int

the limit for the semaphore.

Annotations
@Deprecated
Exceptions
IllegalArgumentException:
if the period is less or equals 0.
TimedSemaphoreback to summary
public TimedSemaphore(final ScheduledExecutorService service, final long timePeriod, final TimeUnit timeUnit, final int limit)

Deprecated

Use builder() and Builder.

Constructs a new instance of TimedSemaphore and initializes it with an executor service, the given time period, and the limit. The executor service will be used for creating a periodic task for monitoring the time period. It can be null, then a default service will be created.

Parameters
service:ScheduledExecutorService

the executor service.

timePeriod:long

the time period.

timeUnit:TimeUnit

the unit for the period.

limit:int

the limit for the semaphore.

Annotations
@Deprecated
Exceptions
IllegalArgumentException:
if the period is less or equals 0.

Method Detail

acquireback to summary
public synchronized void acquire() throws InterruptedException

Acquires a permit from this semaphore. This method will block if the limit for the current period has already been reached. If shutdown() has already been invoked, calling this method will cause an exception. The very first call of this method starts the timer task which monitors the time period set for this TimedSemaphore. From now on the semaphore is active.

Exceptions
InterruptedException:
if the thread gets interrupted.
IllegalStateException:
if this semaphore is already shut down.
acquirePermitback to summary
private boolean acquirePermit()

Internal helper method for acquiring a permit. This method checks whether currently a permit can be acquired and - if so - increases the internal counter. The return value indicates whether a permit could be acquired. This method must be called with the lock of this object held.

Returns:boolean

a flag whether a permit could be acquired.

builderback to summary
public static TimedSemaphore.Builder builder()

Constructs a new Builder.

Returns:TimedSemaphore.Builder

a new Builder.

Since
3.20.0
endOfPeriodback to summary
pack-priv synchronized void endOfPeriod()

The current time period is finished. This method is called by the timer used internally to monitor the time period. It resets the counter and releases the threads waiting for this barrier.

getAcquireCountback to summary
public synchronized int getAcquireCount()

Gets the number of invocations of the acquire() method for the current period. This may be useful for testing or debugging purposes.

Returns:int

the current number of acquire() invocations.

getAvailablePermitsback to summary
public synchronized int getAvailablePermits()

Gets the number of calls to the acquire() method that can still be performed in the current period without blocking. This method can give an indication whether it is safe to call the acquire() method without risking to be suspended. However, there is no guarantee that a subsequent call to acquire() actually is not-blocking because in the meantime other threads may have invoked the semaphore.

Returns:int

the current number of available acquire() calls in the current period.

getAverageCallsPerPeriodback to summary
public synchronized double getAverageCallsPerPeriod()

Gets the average number of successful (i.e. non-blocking) acquire() invocations for the entire life-time of this TimedSemaphore. This method can be used for instance for statistical calculations.

Returns:double

the average number of acquire() invocations per time unit.

getExecutorServiceback to summary
protected ScheduledExecutorService getExecutorService()

Gets the executor service used by this instance.

Returns:ScheduledExecutorService

the executor service.

getLastAcquiresPerPeriodback to summary
public synchronized int getLastAcquiresPerPeriod()

Gets the number of (successful) acquire invocations during the last period. This is the number of times the acquire() method was called without blocking. This can be useful for testing or debugging purposes or to determine a meaningful threshold value. If a limit is set, the value returned by this method won't be greater than this limit.

Returns:int

the number of non-blocking invocations of the acquire() method.

getLimitback to summary
public final synchronized int getLimit()

Gets the limit enforced by this semaphore. The limit determines how many invocations of acquire() are allowed within the monitored period.

Returns:int

the limit.

getPeriodback to summary
public long getPeriod()

Gets the time period. This is the time monitored by this semaphore. Only a given number of invocations of the acquire() method is possible in this period.

Returns:long

the time period.

getUnitback to summary
public TimeUnit getUnit()

Gets the time unit. This is the unit used by getPeriod().

Returns:TimeUnit

the time unit.

isShutdownback to summary
public synchronized boolean isShutdown()

Tests whether the shutdown() method has been called on this object. If this method returns true, this instance cannot be used any longer.

Returns:boolean

a flag whether a shutdown has been performed.

prepareAcquireback to summary
private void prepareAcquire()

Prepares an acquire operation. Checks for the current state and starts the internal timer if necessary. This method must be called with the lock of this object held.

setLimitback to summary
public final synchronized void setLimit(final int limit)

Sets the limit. This is the number of times the acquire() method can be called within the time period specified. If this limit is reached, further invocations of acquire() will block. Setting the limit to a value <= NO_LIMIT will cause the limit to be disabled, i.e. an arbitrary number ofacquire() invocations is allowed in the time period.

Parameters
limit:int

the limit.

shutdownback to summary
public synchronized void shutdown()

Initializes a shutdown. After that the object cannot be used anymore. This method can be invoked an arbitrary number of times. All invocations after the first one do not have any effect.

startTimerback to summary
protected ScheduledFuture<?> startTimer()

Starts the timer. This method is called when acquire() is called for the first time. It schedules a task to be executed at fixed rate to monitor the time period specified.

Returns:ScheduledFuture<?>

a future object representing the task scheduled.

tryAcquireback to summary
public synchronized boolean tryAcquire()

Tries to acquire a permit from this semaphore. If the limit of this semaphore has not yet been reached, a permit is acquired, and this method returns true. Otherwise, this method returns immediately with the result false.

Returns:boolean

true if a permit could be acquired; false otherwise.

Exceptions
IllegalStateException:
if this semaphore is already shut down.
Since
3.5
org.apache.commons.lang3.concurrent back to summary

public Class TimedSemaphore.Builder

extends Object
implements Supplier<TimedSemaphore>
Class Inheritance
All Implemented Interfaces
java.util.function.Supplier

Builds new TimedSemaphore.
Since
3.20.0

Field Summary

Modifier and TypeField and Description
private int
private long
private ScheduledExecutorService
private TimeUnit

Constructor Summary

AccessConstructor and Description
public
Builder()

Constructs a new Builder.

Method Summary

Modifier and TypeMethod and Description
public TimedSemaphore
get()

Implements java.util.function.Supplier.get.

Gets a result.

public TimedSemaphore.Builder

Returns:

this instance.
setLimit
(final int
The limit.
limit
)

Sets the limit.

public TimedSemaphore.Builder

Returns:

this instance.
setPeriod
(final long
The time period.
period
)

Sets the time period.

public TimedSemaphore.Builder

Returns:

this instance.
setService
(final ScheduledExecutorService
The executor service.
service
)

Sets the executor service.

public TimedSemaphore.Builder

Returns:

this instance.
setTimeUnit
(final TimeUnit
The time unit for the period.
timeUnit
)

Sets the time unit for the period.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

limitback to summary
private int limit
periodback to summary
private long period
serviceback to summary
private ScheduledExecutorService service
timeUnitback to summary
private TimeUnit timeUnit

Constructor Detail

Builderback to summary
public Builder()

Constructs a new Builder.

Method Detail

getback to summary
public TimedSemaphore get()

Implements java.util.function.Supplier.get.

Doc from java.util.function.Supplier.get.

Gets a result.

Annotations
@Override
setLimitback to summary
public TimedSemaphore.Builder setLimit(final int limit)

Sets the limit.

Parameters
limit:int

The limit.

Returns:TimedSemaphore.Builder

this instance.

setPeriodback to summary
public TimedSemaphore.Builder setPeriod(final long period)

Sets the time period.

Parameters
period:long

The time period.

Returns:TimedSemaphore.Builder

this instance.

setServiceback to summary
public TimedSemaphore.Builder setService(final ScheduledExecutorService service)

Sets the executor service.

Parameters
service:ScheduledExecutorService

The executor service.

Returns:TimedSemaphore.Builder

this instance.

setTimeUnitback to summary
public TimedSemaphore.Builder setTimeUnit(final TimeUnit timeUnit)

Sets the time unit for the period.

Parameters
timeUnit:TimeUnit

The time unit for the period.

Returns:TimedSemaphore.Builder

this instance.