java - Creating a dynamic (growing/shrinking) thread pool -
i need implement thread pool in java (java.util.concurrent) number of threads @ minimum value when idle, grows upper bound (but never further) when jobs submitted faster finish executing, , shrinks lower bound when jobs done , no more jobs submitted.
how implement that? imagine common usage scenario, apparently java.util.concurrent.executors
factory methods can create fixed-size pools , pools grow unboundedly when many jobs submitted. threadpoolexecutor
class provides corepoolsize
, maximumpoolsize
parameters, documentation seems imply way ever have more corepoolsize
threads @ same time use bounded job queue, in case, if you've reached maximumpoolsize
threads, you'll job rejections have deal yourself? came this:
//pool creation executorservice pool = new threadpoolexecutor(minsize, maxsize, 500, timeunit.milliseconds, new arrayblockingqueue<runnable>(minsize)); ... //submitting jobs (runnable job : ...) { while (true) { try { pool.submit(job); system.out.println("job " + job + ": submitted"); break; } catch (rejectedexecutionexception e) { // maxsize jobs executing concurrently atm.; re-submit new job after short wait system.out.println("job " + job + ": rejected..."); try { thread.sleep(300); } catch (interruptedexception e1) { } } } }
am overlooking something? there better way this? also, depending on one's requirements, might problematic above code not finish until @ least (i think) (total number of jobs) - maxsize
jobs have finished. if want able submit arbitrary number of jobs pool , proceed without waiting of them finish, don't see how without having dedicated "job sumitting" thread manages required unbounded queue hold submitted jobs. afaics, if you're using unbounded queue threadpoolexecutor itself, thread count never grow beyond corepoolsize.
when growing , shrinking comes thread, there 1 name comes mind: cachedthreadpool java.util.concurrent package.
executorservice executor = executors.newcachedthreadpool();
cachedthreadpool() can reuse thread, create new threads when needed. , yes, if thread idle 60 seconds, cachedthreadpool kill it. quite lightweight – growing , shrinking in words!
Comments
Post a Comment