package org.ehcache.impl.internal.executor;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.util.concurrent.Executors.unconfigurableExecutorService;
import static java.util.concurrent.Executors.unconfigurableScheduledExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.ehcache.impl.internal.util.ThreadFactoryUtil;
import org.ehcache.spi.service.ServiceProvider;
import org.ehcache.core.spi.service.ExecutionService;
import org.ehcache.spi.service.Service;
public class OnDemandExecutionService implements ExecutionService {
private static void rejectedExecutionHandler(Runnable r, ThreadPoolExecutor executor) {
boolean interrupted = false;
try {
while (true) {
try {
executor.getQueue().put(r);
return;
} catch (InterruptedException ex) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
@Override
public ScheduledExecutorService getScheduledExecutor(String poolAlias) {
return unconfigurableScheduledExecutorService(Executors.newSingleThreadScheduledExecutor(ThreadFactoryUtil.threadFactory(poolAlias)));
}
@Override
public ExecutorService getOrderedExecutor(String poolAlias, BlockingQueue<Runnable> queue) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, queue, ThreadFactoryUtil.threadFactory(poolAlias), OnDemandExecutionService::rejectedExecutionHandler);
executor.allowCoreThreadTimeOut(true);
return unconfigurableExecutorService(executor);
}
@Override
public ExecutorService getUnorderedExecutor(String poolAlias, BlockingQueue<Runnable> queue) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, queue, ThreadFactoryUtil.threadFactory(poolAlias), OnDemandExecutionService::rejectedExecutionHandler);
executor.allowCoreThreadTimeOut(true);
return unconfigurableExecutorService(executor);
}
@Override
public void start(ServiceProvider<Service> serviceProvider) {
}
@Override
public void stop() {
}
}