title: Resource allocator in Java
body: <p>I have this resource allocator class</p>
  
  <pre><code>public class ResourceAllocator {
  
  ArrayList&lt;Request&gt; queue = new ArrayList&lt;&gt;();
  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() &lt;= 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() &gt; 0) {
              Request req = queue.get(0);
              while (queue.size() &gt; 0 &amp;&amp; 
                      req.getRequest() &lt;= available) {
                  available = available - req.getRequest();
                  req.allocate();
                  queue.remove(0);
                  if (queue.size() &gt; 0) {
                      req = queue.get(0);
                  }
              }
          }
      } finally {
          lock.unlock();
      }
  }
  
  public int size(){
      return queue.size();
  }
  }
  </code></pre>
  
  <p>which is called from a thread</p>
  
  <pre><code>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);
  }
  }
  </code></pre>
  
  <p>And all is fine apart from the fact that resources are allocated FIFO.</p>
  
  <p>Any ideas how could I change this to allow clients with small requests to proceed before clients with large requests, bounded overtaking?</p>