I have this resource allocator class
public class ResourceAllocator {
ArrayList<Request> queue = new ArrayList<>();
Lock lock = new ReentrantLock();
int maxResources;
int available;
public ResourceAllocator(int max) {
maxResources = max;
available = max;
}
public int getMax() {
return maxResources;
}
public void getResources(Request req) {
lock.lock();
try {
if (req.getRequest() <= available) {
available = available - req.getRequest();
req.allocate();
} else {
queue.add(req);
}
} finally {
lock.unlock();
}
}
public void returnResources(int n) {
lock.lock();
try {
available = available + n;
if (queue.size() > 0) {
Request req = queue.get(0);
while (queue.size() > 0 &&
req.getRequest() <= available) {
available = available - req.getRequest();
req.allocate();
queue.remove(0);
if (queue.size() > 0) {
req = queue.get(0);
}
}
}
} finally {
lock.unlock();
}
}
public int size(){
return queue.size();
}
}
which is called from a thread
public class QThread extends Thread {
Semaphore sem = new Semaphore(0);
ResourceAllocator resources;
int number;
public QThread(ResourceAllocator rs, int n) {
resources = rs;
number = n;
}
public void run() {
int items = (int) (Math.random() * resources.getMax()) + 1;
Request req = new Request(sem, items);
resources.getResources(req);
try {
sem.acquire();
} catch (InterruptedException ex) {
}
System.out.printf("Thread %3d got %3d resources\n", number, items);
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
}
resources.returnResources(items);
System.out.printf("Thread %3d returned %3d resources\n", number,items);
}
}
And all is fine apart from the fact that resources are allocated FIFO.
Any ideas how could I change this to allow clients with small requests to proceed before clients with large requests, bounded overtaking?
You can use
PriorityQueuewhich suits best to your needs, then you can implement customComparator(if you think in future you may need a different implementation for sorting) or elseComparablewhich will sort yourRequestso that jobs in terms of size are submitted, executed first.