java - Threadpool task executor timeout for working thread -
i using spring boot , have 1 async method. execute async have below configuration, questions if 5 thread hangs reason , lock application , none of new task executed (it keep accepting). how can set timeout working thread , lets 120 seconds, after timesout , execute new task. (yes using fixed thread pool unbounded queue keep accepting tasks)
@enableasync @configuration public class asyncconfiguration implements asyncconfigurer { @override public executor getasyncexecutor() { threadpooltaskexecutor taskexecutor = new threadpooltaskexecutor(); taskexecutor.setcorepoolsize(5); taskexecutor.setmaxpoolsize(5); taskexecutor.initialize(); return taskexecutor; } @override public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() { return new simpleasyncuncaughtexceptionhandler(); }
}
you can create executor like:
static class timeoutexecutorservice extends completableexecutors.delegatingcompletableexecutorservice { private final duration timeout; private final scheduledexecutorservice schedulerexecutor; timeoutexecutorservice(executorservice delegate, duration timeout) { super(delegate); this.timeout = timeout; schedulerexecutor = executors.newscheduledthreadpool(1); } @override public <t> completablefuture<t> submit(callable<t> task) { completablefuture<t> cf = new completablefuture<>(); future<?> future = delegate.submit(() -> { try { cf.complete(task.call()); } catch (cancellationexception e) { cf.cancel(true); } catch (throwable ex) { cf.completeexceptionally(ex); } }); schedulerexecutor.schedule(() -> { if (!cf.isdone()) { cf.completeexceptionally(new timeoutexception("timeout after " + timeout)); future.cancel(true); } }, timeout.tomillis(), timeunit.milliseconds); return cf; } }
then, create new bean named timed
@bean(name = "timed") public executor timeoutexecutor() { threadfactory threadfactory = new threadfactorybuilder().setnameformat("timed-%d").build(); return timedcompletables.timed(executors.newfixedthreadpool(10, threadfactory), duration.ofseconds(2)); }
and, try use executor
execute async tasks.
or, try change code fixsizethreadpool
build own thread pool executor.
Comments
Post a Comment