Java实现超时机制

2019-09-26  本文已影响0人  ZackJiang

Java实现超时机制

package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class TimeoutUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeoutUtil.class);

    private static ExecutorService executor = Executors.newSingleThreadExecutor();

    public static <T> T process(Callable<T> task, long timeout) {
        if (task == null) {
            return null;
        }
        Future<T> futureRet = executor.submit(task);
        try {
            T ret = futureRet.get(timeout, TimeUnit.SECONDS);
            return ret;
        } catch (InterruptedException e) {
            LOGGER.error("Interrupt Exception", e);
        } catch (ExecutionException e) {
            LOGGER.error("Task execute exception", e);
        } catch (TimeoutException e) {
            LOGGER.warn("Process Timeout");
            if (futureRet != null && !futureRet.isCancelled()) {
                futureRet.cancel(true);
            }
        }
        return null;
    }
}
上一篇下一篇

猜你喜欢

热点阅读