You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "TeeleTitan (via GitHub)" <gi...@apache.org> on 2025/10/26 11:51:16 UTC

[PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

TeeleTitan opened a new pull request, #1475:
URL: https://github.com/apache/commons-lang/pull/1475

   <!--
     Licensed to the Apache Software Foundation (ASF) under one
     or more contributor license agreements.  See the NOTICE file
     distributed with this work for additional information
     regarding copyright ownership.  The ASF licenses this file
     to you under the Apache License, Version 2.0 (the
     "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at
   
       https://www.apache.org/licenses/LICENSE-2.0
   
     Unless required by applicable law or agreed to in writing,
     software distributed under the License is distributed on an
     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
     specific language governing permissions and limitations
     under the License.
   -->
   
   Thanks for your contribution to [Apache Commons](https://commons.apache.org/)! Your help is appreciated!
   
   Before you push a pull request, review this list:
   
   - [X] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
   - [X] Read the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) if you use Artificial Intelligence (AI).
   - [X] I used AI to create any part of, or all of, this pull request.
   - [X] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
   - [X] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
   - [X] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
   - [X] Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.
   
   **Description of Issue**
   This PR adresses "LANG[1790] - Fairness setting in TimedSemaphore" :  https://issues.apache.org/jira/browse/LANG-1790
   
   The existing TimedSemaphore implementation provides rate limiting across fixed time periods, but uses manual synchronisation (wait() / notifyAll()) for blocking. Under heavy contention, this approach can lead to non-deterministic thread ordering and inconsistent blocking behaviour. Additionally, dynamically changing the limit during an active period did not immediately update the available permits, allowing extra acquires within that window.
   
   **Implementation**
   Fairness Support: Added a new builder flag that enables optional FIFO fairness for permit acquires. Fairness is handled by a backing 'java.util.concurrent.Semaphore' constructed with the fair flag, ensuring that waiting threads acquire permits in order.
   Refactored Permit Management: Replaced counter synchronisation with a dedicated Semaphore to manage permits. The semaphore now handles all blocking, acquisition, and wake-up behavior, simplifying the internal logic and improving correctness under contention.
   Dynamic Limit Adjustment: Updated setLimit(int) to immediately resize the active permit capacity for the current period.
   End of period refill: The endOfPeriod() method now explicitly tops up the semaphore to the configured limit at each interval, ensuring clean period rollover and accurate permit replenishment.
   
   **Validation and Testing**
   1) FIFO ordering , Method: testFairnessFIFOOrdering_acrossPeriods()
   When fair = true, and the limit is set to 1, threads that arrive earlier should be served earlier across consecutive periods. The method acquires T1 (thread 1) first, then T2 and T3. Through manually calling endofPeriod() twice, the completion order asserted is as follows:
       1) T1 
       2) T2
       3) T3
   This test proves that the fairness flag actually allows for FIFO queuing
   
   2) Dynamic resizing of the limit , Method: testSetLimitResizesBucketWithinPeriod()
   It checks that, in the middle of a period, given a decrease in the limit takes place, the code immediately prevents further acquires within the same period if the new limit has already been reached. It starts with limit = 3, acquires twice, then it decreases the limit to 1. It first tries tryAcquire(), which is expected to fail. Upon failure, endofPeriod() is called, and only 1 permit should be available in the new period.
   This validates the behaviour of setLimit() and the coordination between statistical counters.
   
   3) Period rollover and unblocking , Method: testEndOfPeriodTopUpReleasesBlockedThreads()
   It checks that endofPeriod() refills permits to the configured limit, and ‘wakes’ blocked threads through notifyAll(), which allows for the next thread waiting to acquire. It starts with assignment limit = 1, T1 acquires and T2 blocks. After manually calling endOfPeriod(), T2 should complete straight away.
   This confirms the new top-up and unblocking logic are correctly implemented
   
   4) NO_LIMIT short circuit with fairness , Method: testAcquireNoLimitWithFairnessEnabled()
   Through ‘limit <= NO_LIMIT’, acquire() never blocks, even when fairness is enabled. It does this via building through Builder with NO_LIMIT and assuring fair = true. Then, acquire() is called many times without waiting for period rollover
   This confirms the short circuit path ignores the Semaphore cleanly and remains viable alongside the fairness option
   
   5) Permits after increase , Method: testGetAvailablePermitsAfterLimitIncreaseWithinPeriod()
   It checks that whether the limit increase in the middle of a period influences the remaining (non-blocking) available permits, reported via getAvaliablePermits() alongside tryAcquire(). It does this as, when limit = 1, acquire occurs once, then the limit increase to 3, then two more non-blocking acquires should now pass and be valid, and then finally the 4th one should fail
   This verifies that counters and semaphore capacity stay consistent when upscaling the limit during a period
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub) via issues" <is...@commons.apache.org>.
garydgregory closed pull request #1475: [LANG-1656] Fairness setting in TimedSemaphore
URL: https://github.com/apache/commons-lang/pull/1475


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on code in PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#discussion_r2465316488


##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -235,10 +249,18 @@ public static Builder builder() {
     /** A flag whether shutdown() was called. */
     private boolean shutdown; // @GuardedBy("this")
 
+    /** Fairness mode checker */
+    private final boolean fair;
+
+    /** Backing semaphore that enforces blocking and (optionally) FIFO fairness. */
+    private final Semaphore semaphore;
+

Review Comment:
   No need for 2 blank lines. One is plenty here.



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -179,6 +181,17 @@ public Builder setTimeUnit(final TimeUnit timeUnit) {
             this.timeUnit = timeUnit;
             return this;
         }
+
+        /**
+         * ADDED: Enables or disables FIFO fairness

Review Comment:
   The javadoc for a setter should read: "Sets ...". You signify that a public or protected API was added with the Javadoc `since` tag.
   
   A sentence ends in a period: "Sets whether the instance is fair."
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub) via issues" <is...@commons.apache.org>.
garydgregory commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-6900175920

   Closing: Implemented in version `3.22.0`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "aherbert (via GitHub)" <gi...@apache.org>.
aherbert commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-3451116897

   I think this is an improvement. However it is difficult to write concurrent code and there may be issues I did not notice. The class seems to have issues around the computation of permits, acquires and limits as it makes some assumptions on the limit based on whether it is zero or negative but then does not guard the limit to the range [0, MAX_VALUE]. Thus the limit can be set to a large negative value and break existing functionality.
   
   I noted that the fair flag is not enforced when using the semaphore as it uses `tryAcquire()` which does not respect fairness. So the current unit test is not robust enough to detect this.
   
   Also not changed in the PR, but it broken in the current code is the computation in the method `getAvailablePermits()`. This method can return negative values which do not make sense. It should return a value in the positive range if there is a configured limit. If the limit is disabled then it should return either -1 as a documented flag or Integer.MAX_VALUE to state that you can have as many permits as you desire. I prefer returning MAX_VALUE so that clients can compare this value to any positive number of permits that they desire.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-3467578155

   Hello @TeeleTitan 
   
   Would you please fix the builds and address comments?
   
   Thank you


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-3450822480

   @ppkarwasz , @chtompki or @aherbert 
   Any thoughts on this PR?
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "chtompki (via GitHub)" <gi...@apache.org>.
chtompki commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-3451614951

   I love you guys!On Oct 27, 2025, at 8:48 AM, Alex Herbert ***@***.***> wrote:aherbert left a comment (apache/commons-lang#1475)
   I think this is an improvement. However it is difficult to write concurrent code and there may be issues I did not notice. The class seems to have issues around the computation of permits, acquires and limits as it makes some assumptions on the limit based on whether it is zero or negative but then does not guard the limit to the range [0, MAX_VALUE]. Thus the limit can be set to a large negative value and break existing functionality.
   I noted that the fair flag is not enforced when using the semaphore as it uses tryAcquire() which does not respect fairness. So the current unit test is not robust enough to detect this.
   Also not changed in the PR, but it broken in the current code is the computation in the method getAvailablePermits(). This method can return negative values which do not make sense. It should return a value in the positive range if there is a configured limit. If the limit is disabled then it should return either -1 as a documented flag or Integer.MAX_VALUE to state that you can have as many permits as you desire. I prefer returning MAX_VALUE so that clients can compare this value to any positive number of permits that they desire.
   
   —Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: ***@***.***>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#issuecomment-3693359001

   See also PR #1544 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [LANG-1656] Fairness setting in TimedSemaphore [commons-lang]

Posted by "aherbert (via GitHub)" <gi...@apache.org>.
aherbert commented on code in PR #1475:
URL: https://github.com/apache/commons-lang/pull/1475#discussion_r2465373467


##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -123,6 +124,7 @@ public static class Builder implements Supplier<TimedSemaphore> {
         private long period;
         private TimeUnit timeUnit;
         private int limit;
+        private boolean fair = false;

Review Comment:
   Remove the default initialiser.



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -290,41 +314,48 @@ public TimedSemaphore(final ScheduledExecutorService service, final long timePer
      * @throws InterruptedException  if the thread gets interrupted.
      * @throws IllegalStateException if this semaphore is already shut down.
      */
-    public synchronized void acquire() throws InterruptedException {
+    public void acquire() throws InterruptedException {
         prepareAcquire();
-        boolean canPass;
-        do {
-            canPass = acquirePermit();
-            if (!canPass) {
-                wait();
+        if (getLimit() <= NO_LIMIT) {
+            synchronized (this) {
+                acquireCount++;
+            }
+            return;
+        }
+        if (semaphore.tryAcquire()) {
+            synchronized (this) {
+                acquireCount++;
+            }
+            return;
+        }
+        for (;;) {
+            synchronized (this) {
+                if (semaphore.tryAcquire()) {
+                    acquireCount++;
+                    return;
+                }
+                this.wait();
             }
-        } while (!canPass);
-    }
-
-    /**
-     * 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.
-     *
-     * @return a flag whether a permit could be acquired.
-     */
-    private boolean acquirePermit() {
-        if (getLimit() <= NO_LIMIT || acquireCount < getLimit()) {
-            acquireCount++;
-            return true;
         }
-        return false;
     }
 
     /**
      * 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.
      */
-    synchronized void endOfPeriod() {
+    void endOfPeriod() {
         lastCallsPerPeriod = acquireCount;
         totalAcquireCount += acquireCount;
         periodCount++;
         acquireCount = 0;
-        notifyAll();
+        final int avail = semaphore.availablePermits();
+        final int toRelease = Math.max(0, getLimit() - avail);

Review Comment:
   This will overflow if I use `setLimit(Integer.MIN_VALUE)` so we need some better guarding on the limit range.



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -437,6 +469,17 @@ private void prepareAcquire() {
      */
     public final synchronized void setLimit(final int limit) {
         this.limit = limit;
+
+        if (semaphore != null) {

Review Comment:
   IIUC the semaphor is only null when `setLimit` is called in the constructor. I would avoid the call to this method in the constructor and set the limit directly. The null check can then be removed here.
   
   One caveat here is that limit is checked for <= 0 in several places to change behaviour. There is no usage of limit when it is negative. However setting it to Integer.MIN_VALUE will cause some of the difference computations to overflow. I would add a guard for limit when setting it to `max(NO_LIMIT, limit)`.
   
   In order to guard the limit to the positive range it could be set only within a private method:
   ```java
   private void updateLimit(int value) {
       limit = Math.max(0, value);
   }
   ```



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -290,41 +314,48 @@ public TimedSemaphore(final ScheduledExecutorService service, final long timePer
      * @throws InterruptedException  if the thread gets interrupted.
      * @throws IllegalStateException if this semaphore is already shut down.
      */
-    public synchronized void acquire() throws InterruptedException {
+    public void acquire() throws InterruptedException {
         prepareAcquire();
-        boolean canPass;
-        do {
-            canPass = acquirePermit();
-            if (!canPass) {
-                wait();
+        if (getLimit() <= NO_LIMIT) {
+            synchronized (this) {
+                acquireCount++;
+            }
+            return;
+        }
+        if (semaphore.tryAcquire()) {

Review Comment:
   Javadoc for Semaphor states we should use [tryAcquire(0, TimeUnit.SECONDS)](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html#tryAcquire-long-java.util.concurrent.TimeUnit-) to preserve fairness. So this behaviour should change based on the constructor flag, e.g. using a helper method:
   
   ```java
   private boolean fairTryAcquire() throws InterruptedException {
       return fair ? semaphore.tryAcquire(0, TimeUnit.SECONDS) : semaphore.tryAcquire();
   }
   ```



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -475,8 +516,17 @@ protected ScheduledFuture<?> startTimer() {
      * @throws IllegalStateException if this semaphore is already shut down.
      * @since 3.5
      */
-    public synchronized boolean tryAcquire() {
+    public boolean tryAcquire() {
         prepareAcquire();
-        return acquirePermit();
+        if (getLimit() <= NO_LIMIT) {
+            synchronized (this) { acquireCount++; }
+            return true;
+        }
+
+        final boolean ok = semaphore.tryAcquire();

Review Comment:
   Guard this tryAcquire with the fair flag. However in this method it would add a throws InterruptedException to the API. So it should be documented as not respecting the fair policy, e.g. copy the wording from the Semaphore javadoc on `tryAcquire`.



##########
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java:
##########
@@ -235,10 +249,18 @@ public static Builder builder() {
     /** A flag whether shutdown() was called. */
     private boolean shutdown; // @GuardedBy("this")
 
+    /** Fairness mode checker */
+    private final boolean fair;

Review Comment:
   This flag is never used outside the constructor. Currently it could be dropped. However if we wish to preserve fairness then it should be used in `acquire`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org