I’m looking for a java thread-pool, that won’t run more threads simultaneously than there are cores in the system. This service is normally provided by a ThreadPoolExecutor using a BlockingQueue.
However, if a new thread is scheduled to execute, I want the new thread to pre-empt one of the already running threads, and add the the pre-empted thread (in a suspended state) to a task queue, so it can be resumed as soon as the new thread is finished.
Any suggestions?
I would make a subclass of ThreadPoolExecutor.
When you setup your ThreadPoolExecutor you want to set the
corePoolSizeand themaximumPoolSizetoRuntime.getRuntime().availableProcessors()(Look atExecutors.newFixedThreadPool()to see why this works).Next you want to make sure that your
Queuealso implementsDeque.LinkedBlockingDequeis an example but you should shop around to see which one will work best for you. ADequeallows you to get stack like LIFO behavior which is exactly what you want.Since everything (
submit(),invokeAll()) funnels throughexecute()you will want to override this method. Basically do what you described above:Check if all threads are running. If not simply start the new runnable on an available thread. If all the threads are already running then you need to find the one running the oldest runnable, stop the runnable, re-queue the runnable somewhere (maybe at the beginning?), and then start your new runnable.