My problem is this: I can have a maximum of three concurrent tasks running. These tasks can process 1 to 100 jobs simultaneously. I have many threads constantly submitting single jobs, and I want to respond to them as fast as possible. The time taken to process 100 jobs in one task is the same as it takes to process 1 job in one task. Jobs come in at random intervals. Threads that submit jobs need to block until the job is done, or a timeout is hit. Responding quickly to the threads submitting jobs is the driver here.
So my current logic is this: If there are < 3 tasks running, and a job arrives, create a new task to process just that job on it's own. If there are 3 tasks running, put the job in a queue and wait until another task finishes, then take all the jobs from the queue (limit 100) and create a task to process all of them.
I'm just not quite sure the best way to set this up in Java. I created a simple semaphore versions which works fine but does not take advantage of the ability to submit job simultaneously together. How best should I expand this to fully meet my requirements? (there is no requirement to use a semaphore, it's just what I have so far).
private static final Semaphore semaphore = new Semaphore(3);
public static Response doJob(Job job) throws Exception
{
final boolean tryAcquire = this.semaphore.tryAcquire(this.maxWaitTime, TimeUnit.MILLISECONDS);
if (tryAcquire)
{
try
{
return doJobInNewTask(job); // we'd actually like to do all the jobs which are queued up waiting for the semaphore (if there are any)
}
finally
{
this.semaphore.release()
}
}
}