java - Maximum wait time in queue in ExecutorService -
is there way set maximum wait time on executor services ?!
for example when pass 2 while true runnable singlethreadexecutor
first 1 work forever , , second 1 wait ever.
i expect got timeoutexception second runnable.
public static void main(string[] args) throws ioexception { executorservice executor = executors.newsinglethreadexecutor(); (int = 0; < 2; i++) { int finali = i; executor.execute(new runnable() { @override public void run() { while (true) { try { system.out.println("#"+ finali + " runnable !"); thread.sleep(1000); } catch (exception e) { e.printstacktrace(); } } } }); } }
is there way set maximum wait time on executor services ?!
if talking waiting job start run, answer unfortunately "not easily". there ways can using queue in threadpoolexecutor
considered hacks , aren't recommended. extend threadpoolexecutor
complicated.
one [better] solution manage queue externally.
// synchronous queue waits take() queue before returning final blockingqueue<runnable> jobqueue = new synchronousqueue<runnable>(); ... // submit of threads jobs queue run executor.execute(new runnable() { @override public void run() { while (!thread.currentthread.isinterrupted()) { try { runnable job = jobqueue.take(); job.run(); } catch (interruptedexception ie) { // recommended thread.currentthread().interrupt(); return; } } } }); ... // can try add job queue if full, offer may timeout if (!queue.offer(new runnable() { ... }, 2000, timeunit.seconds)) { // timed out }
hope helps.
Comments
Post a Comment