简体   繁体   中英

Java Threadpools with competeting queues

I have a situation where I'd like to use an extension of Java's fixed thread pools. I have N groups of runnable objects that I'd like to compete for resources. However, I'd like the total number of threads used to remain constant. The way that I would like this to work is outlined here

  1. Allocate an object with N threads and M queues;
  2. Schedule job n on queue m.
  3. Have a pointer to the first queue Repeat a. If the maximum number of threads is currently in use wait. b. Pop off a job on the current queue c. Move the pointer one queue over (or from the last queue to the first)

First, does something like this already exist? Second if not, I'm nervous about writing my own because I know writing my own thread pools can be dangerous. Can anyone point me to some good examples for writing my own.

Your best bet is probably creating your own implementation of a Queue that cycles through other queues. For example (in pseudo-code):

class CyclicQueue { Queue queues[]; int current = 0;

CyclicQueue(int size) {
  queues = new Queue[size];

  for(int i=0; i<size; i++)
    queues[i] = new LinkedList<T>();
}

T get() {
  int i = current;
  T value;
  while( (value = queues[i].poll() == null) {
    i++;
    if(i == current)
      return null;
  }
  return value;
}

}

Of course, with this, if you want blocking you'll need to add that in yourself.

In which case, you'll probably want a custom Queue for each queue which can notify the parent queue that value has been added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM