Last active
February 3, 2025 01:09
-
-
Save aerodame/097e2ab8944758f21fa5af58246623d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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