Skip to content

Commit

Permalink
Revert use of AtomicInteger in AdjustableSemaphore
Browse files Browse the repository at this point in the history
  • Loading branch information
yashmayya committed Jan 23, 2025
1 parent 5a9e978 commit 53e22af
Showing 1 changed file with 9 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,44 +20,43 @@

import com.google.common.base.Preconditions;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;


/**
* A semaphore that allows adjusting the number of permits in a non-blocking way.
*/
public class AdjustableSemaphore extends Semaphore {

private final AtomicInteger _totalPermits;
private volatile int _totalPermits;

public AdjustableSemaphore(int permits) {
super(permits);
_totalPermits = new AtomicInteger(permits);
_totalPermits = permits;
}

public AdjustableSemaphore(int permits, boolean fair) {
super(permits, fair);
_totalPermits = new AtomicInteger(permits);
_totalPermits = permits;
}

/**
* Sets the total number of permits to the given value without blocking.
*/
public void setPermits(int permits) {
Preconditions.checkArgument(permits > 0, "Permits must be a positive integer");
if (permits < _totalPermits.get()) {
reducePermits(_totalPermits.get() - permits);
} else if (permits > _totalPermits.get()) {
release(permits - _totalPermits.get());
if (permits < _totalPermits) {
reducePermits(_totalPermits - permits);
} else if (permits > _totalPermits) {
release(permits - _totalPermits);
}
_totalPermits.set(permits);
_totalPermits = permits;
}

/**
* Returns the total number of permits (as opposed to just the number of available permits returned by
* {@link #availablePermits()}).
*/
public int getTotalPermits() {
return _totalPermits.get();
return _totalPermits;
}
}

0 comments on commit 53e22af

Please sign in to comment.