Search code examples
javaconcurrencyqueuethreadpool

How to create ThreadPool that executes random task from queue


ThreadPool's uses BlockingQueue to store tasks in queue.

I want executor that takes random task from queue. So first task and last task in queue have equal chances to be taken from.

Is that possible to do?


Solution

  • Yes it is technically possible to implement a thread pool which chooses the next task randomly. You can instantiate ThreadPool with a caller-supplied queue.

    While it seems strange (even dangerous or subversive!) to some people1, a Queue is not necessarily FIFO. Indeed the javadoc for Queue states:

    Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

    So all you need to do to implement random thread pool behavior is to implement your own BlockingQueue class with a take() that selects the element randomly.

    Alternatively, @Ben Manes' idea is use a PriorityBlockingQueue and assign random priorities. (This is simpler, but there is an overhead in keeping the queue heapified: O(1) on average, but O(logN) in the worst case.)


    1 - Actually, in the real world queues are largely a social convention. Some cultures apparently don't follow this convention; e.g. https://www.thelocal.it/20150410/my-italian-habits-that-foreigners-just-dont-get. By contrast: https://www.standard.co.uk/lifestyle/london-life/british-people-display-amazing-queuing-etiquette-without-being-told-a3528366.html