Skip to content

Instantly share code, notes, and snippets.

@aerodame
Last active February 3, 2025 01:09
Show Gist options
  • Save aerodame/097e2ab8944758f21fa5af58246623d9 to your computer and use it in GitHub Desktop.
Save aerodame/097e2ab8944758f21fa5af58246623d9 to your computer and use it in GitHub Desktop.
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ResourceAllocator {
private boolean busy;
private final Lock lock = new ReentrantLock();
private final Condition resourceAvailable = lock.newCondition();
public ResourceAllocator() {
this.busy = false;
}
public void acquire(long timeoutMillis) throws InterruptedException {
lock.lock();
try {
if (busy) {
if(!resourceAvailable.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS))
System.out.println(" Timed out waiting for resource.");
}
if(!busy){
busy = true;
}
} finally {
lock.unlock();
}
}
public void release() {
lock.lock();
try {
busy = false;
resourceAvailable.signal();
} finally {
lock.unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment