码迷,mamicode.com
首页 > 其他好文 > 详细

ExecutorService +FutureTask 方法体超时

时间:2015-08-06 12:50:51      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

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;

	}

  

ExecutorService +FutureTask 方法体超时

标签:

原文地址:http://www.cnblogs.com/lgtrajectory/p/4707361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!