ExecutorService +FutureTask 方法体超时

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.Callable;

import com.piccapp.dto.entity.UFaceInfo;
import com.sinosoft.base.component.face.WebSMethodPool;
import com.sinosoft.base.component.face.WebServiceUtil;
import com.sinosoft.base.exception.DataVerifyException;

public class CallWebServiceInTime implements Callable{
	public CallWebServiceInTime(UFaceInfo configure,Map reqxml){
		this.configure=configure;
		this.reqxml=reqxml;
	}
	UFaceInfo configure =null;
	Map reqxml = null;
	public UFaceInfo getConfigure() {
		return configure;
	}
	public void setConfigure(UFaceInfo configure) {
		this.configure = configure;
	}
	public Map getReqxml() {
		return reqxml;
	}
	public void setReqxml(Map reqxml) {
		this.reqxml = reqxml;
	}
	@Override
	public Object call() throws Exception {
		String webclass=configure.getFaceid();
		String invokeMethod =configure.getMethod();//"hxMPSCallService";//
		if(invokeMethod==null){
			throw new DataVerifyException("WebService接口地址有误!请检查WebService接口地址配置!webclass:"+webclass+"  invokeMethod:"+invokeMethod);
		}
		WebServiceUtil webSerUtil = WebSMethodPool.getWebOjbect();
		Method md = WebSMethodPool.getMethod(configure.getFaceid(),invokeMethod);
		Object rsp= md.invoke(webSerUtil,reqxml);
		return (String)rsp;
	}

}

  调用部分:

  

public static String timeOutMethod(Callable ca,int timeout) throws InterruptedException, ExecutionException, TimeoutException {
		String result="";
	    ExecutorService executor = Executors.newSingleThreadExecutor();  
	    FutureTask<String> future =  
	           new FutureTask<String>(ca);  
	    executor.execute(future);  
	    //在这里可以做别的任何事情  
	    try {  
	      result = future.get(timeout, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果  
	      future.cancel(true);
	    } catch (InterruptedException e) {  
	    	future.cancel(true); 
	    	throw e;
	    } catch (ExecutionException e) {  
	    	future.cancel(true);  
	    	throw e;
	    } catch (TimeoutException e) {  
	    	future.cancel(true);
	    	throw e;
	    } finally {  
	        executor.shutdown();  
	    }  
	    return  result;

	}

  

转载于:https://www.cnblogs.com/lgtrajectory/p/4707361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值