美文网首页
Java实现超时机制

Java实现超时机制

作者: ZackJiang | 来源:发表于2019-09-26 21:17 被阅读0次

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;
    }
}

相关文章

网友评论

      本文标题:Java实现超时机制

      本文链接:https://www.haomeiwen.com/subject/vwwnuctx.html