Java给方法设置超时

package com.sfpay.console.util;

......
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
......

/**
 * 类说明:
* 临时数据提取模块Handler *

* 详细描述:
* Common Util *

* @author 80003614 * CreateDate: 2018-12-3 */ @Component("dataExtrComHandler") public class DataExtrComHandler { ...... /** * 执行sql查询,加载查询内容到内存 * @param connection 数据库连接对象 * @param querySql 要执行的sql语句 * @return * @throws Exception */ public List executeDBQuery(final Connection connection, final String querySql) throws Exception { // 该处需防止内存溢出,后期应优化。 // ArrayListHandler:将查询的结果,每一行先封装到Object数组中,然后将数据存入List集合 ExecutorService executor = Executors.newSingleThreadExecutor(); FutureTask> future = new FutureTask>(new Callable>() { @Override public List call() throws Exception {// 执行sql QueryRunner queryRunner = new QueryRunner(); List data = queryRunner.query(connection, querySql, new ArrayListHandler()); // Thread.sleep(11000); return data; } }); String exeSqlTimeout = null; try { executor.execute(future); // 获取数据库规定的query timeout值 //exeSqlTimeout = sysParaCfgMapper.selectParaValue("EXE-SQL-TIMEOUT-DURATION"); List result = future.get(1000*60, TimeUnit.MILLISECONDS); return result; } catch (TimeoutException e) { // sql执行超时 throw new TimeoutException( "Sql执行超时!系统规定Sql执行时间不能超过" + (Long.parseLong(exeSqlTimeout) / 1000 / 60) + "分钟..."); } catch (Exception e) { throw new RuntimeException("Sql执行异常:" + e.getMessage()); } finally { future.cancel(true); executor.shutdown(); } } ...... }

来源:https://blog.csdn.net/ithouse/article/details/78257418

你可能感兴趣的:(java)