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

Clarify Semaphore.drainPermits behavior when current permits are negative

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 9
    • None
    • core-libs

      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;
                  }
              }

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

              Created:
              Updated:
              Resolved: