Иногда я получаю текущее исключение:Execution Service Java
[java.util.concurrent.RejectedExecutionException: Task [email protected]6c196 rejected from [email protected][Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]]
Я зову runAndAwaitResult()
предельную функцию его 100мс. Если результаты были успешно получены и готовы, я завершаю ExecuorService, если превышен тайм-аут. Я получаю результаты и отключая сервис. Но иногда я получаю это исключение. Как я должен справиться с этим или как лучше всего прекратить обслуживание, чтобы избежать такого исключения. Примечание. Я не могу дождаться недолгого отключения. У меня всего лишь 100 мс для обеих заданий.
try{
generalPersonalisationHandler = new GeneralPersonalisationHandler(resourceStack);
com.company.personalisation.jobs.result.GeneralPersonalisationResult result = timeLimiter.callWithTimeout(new Callable<com.company.personalisation.jobs.result.GeneralPersonalisationResult>() {
@Override
public com.company.personalisation.jobs.result.GeneralPersonalisationResult call() throws Exception {
com.company.personalisation.jobs.result.GeneralPersonalisationResult result = generalPersonalisationHandler.runAndAwaitResults(customerCookie);
generalPersonalisationHandler.shutdown();
return result;
}
}, timeout, TimeUnit.MILLISECONDS, true);
PersonalisationData response = transformAvailableResults(result);
return response;
}
catch (UncheckedTimeoutException e) {
String errorMsg = String.format("TIMEOUT for RunGeneralPersonalisation() execution time has exceeded maximum limit of: [%s] ms", timeout);
ErrorLogger.error(errorMsg, e);
com.company.personalisation.jobs.result.GeneralPersonalisationResult result = generalPersonalisationHandler.returnAvailableResults();
generalPersonalisationHandler.shutdown();
return transformAvailableResults(result);
}
GeneralPersonalisationHandler.java
public class GeneralPersonalisationHandler {
private GeneralPersonalisationResult generalPersonalisationResult;
private final int SUBMITTED_JOBS = 2;
private CompletionService<JobResult> completionService;
private ResourceStack resourceStack;
private ExecutorService executor;
public GeneralPersonalisationHandler(ResourceStack resourceStack){
this.executor = Executors.newFixedThreadPool(SUBMITTED_JOBS);
this.completionService = new ExecutorCompletionService<JobResult>(executor);
this.resourceStack = resourceStack;
}
public GeneralPersonalisationResult runAndAwaitResults(String customerCookie) throws Exception {
Job customerEventsJob = new CustomerEventsJob(customerCookie, resourceStack);
Job customerInfoJob = new CustomerPersonalInfoJob(customerCookie, resourceStack);
completionService.submit(customerInfoJob);
completionService.submit(customerEventsJob);
generalPersonalisationResult = new GeneralPersonalisationResult();
for (int handledJobs = 0; handledJobs < SUBMITTED_JOBS; handledJobs++) {
Future<JobResult> result = completionService.take();
JobResult jobResult = result.get();
if (jobResult instanceof CustomerPersonalInfoJobResult) {
CustomerPersonalInfoJobResult customerPersonalInfoJobResult = (CustomerPersonalInfoJobResult) jobResult;
generalPersonalisationResult.setCustomerPersonalInfoJobResult(customerPersonalInfoJobResult);
}
if (jobResult instanceof CustomerEventsJobResult) {
CustomerEventsJobResult customerEventsJobResult = (CustomerEventsJobResult) jobResult;
generalPersonalisationResult.setCustomerEventsJobResult(customerEventsJobResult);
}
}
}
return generalPersonalisationResult;
}
public GeneralPersonalisationResult returnAvailableResults(){
return this.generalPersonalisationResult;
}
public void shutdown(){
if(!this.executor.isShutdown()) {
this.executor.shutdown();
}
}
}
Спасибо за любую помощь!
Возможно, вы правы, я завершу создание экземпляра 'GeneralPersonalisationHandler' в другой класс, чтобы другие потоки не могли получить доступ к тому же самому исполнителю. Считаете ли вы, что это звучит разумно и поможет? –
У меня нет полного видения вашего проекта, но я бы посоветовал использовать одного исполнителя и заботиться об отключении. В любом случае вы можете попробовать свой подход, но имейте в виду, постоянные исполнители пула сохраняют все потоки до выключения. –