Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8169272

Clarify Semaphore.drainPermits behavior when current permits are negative

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 9
    • Component/s: core-libs
    • Labels:

      Description

      According to description for java.util.concurrent.Semaphore it is ok to create a Semaphore with negative amount of permits. Moreover, all Semaphore's methods (including reducePermits, release, etc) works with negative amount of permits correctly (don't give permits until amount became more than zero, etc). Except drainPermits.
      If Semaphore has less than zero permits, drainPermits returns negative value (that maybe considered as ok), but also drainPermits raises permits to zero, that is definitely an error.
      Suggested fix is quite simple:
      Current code:
             final int drainPermits() {
                  for (;;) {
                      int current = getState();
                      if (current == 0 || compareAndSetState(current, 0))
                          return current;
                  }
              }

      Fixed code should be:
             final int drainPermits() {
                  for (;;) {
                      int current = getState();
                      if (current <= 0 )
                         return 0;
                      if (compareAndSetState(current, 0))
                          return current;
                  }
              }

        Attachments

          Activity

            People

            • Assignee:
              martin Martin Buchholz
              Reporter:
              skuksenko Sergey Kuksenko
            • Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: