当前位置: 代码迷 >> J2SE >> 用Future兑现Timeout,Call方法已经返回,但Future.get方法没有得到,而出了timeoutException
  详细解决方案

用Future兑现Timeout,Call方法已经返回,但Future.get方法没有得到,而出了timeoutException

热度:5273   发布时间:2013-02-25 00:00:00.0
用Future实现Timeout,Call方法已经返回,但Future.get方法没有得到,而出了timeoutException
如题,用java的Future接口去实现socket阻塞read的timeout功能。可能有时call方法返回了,外面还是得不到


ExecutorService receiveExecutor = Executors.newSingleThreadExecutor(); 

FutureTask<CommCodec.Frame> receiveFuture=new FutureTask<CommCodec.Frame>(new Callable<CommCodec.Frame>() {

public Frame call() throws Exception {
// TODO Auto-generated method stub
Frame recFrame=null;
byte[] resultBuffer = new byte[1024];

int receiveCount=0;

try {
while(true)
{
byte[] receivedBuffer=new byte[512];
int size = mInputStream.read(receivedBuffer);
System.arraycopy(receivedBuffer, 0, resultBuffer, receiveCount, size);
receiveCount+=size;

recFrame=CommCodec.decodeBuffer(resultBuffer);
if(recFrame != null && recFrame.getType() != Frame.TYPE_UNKNOWN)
{
receivedBuffer=null;
Log.d(TAG, "Bluetooth.recFrame.getType = "+recFrame.getType()+"....received.bytes = "+Util.toHex(resultBuffer));

return recFrame;
}
}


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resultBuffer=null;
return recFrame;
}
});

receiveExecutor.execute(receiveFuture); 

Frame fuFrame=null;
try {  
fuFrame = receiveFuture.get(timeout, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒
} catch (InterruptedException e) { 
Log.e(TAG, "InterruptedException...");
receiveFuture.cancel(true);  
} catch (ExecutionException e) { 
Log.e(TAG, "ExecutionException...");
receiveFuture.cancel(true);  
} catch (TimeoutException e) {  
Log.e(TAG, "TimeoutException...");
receiveFuture.cancel(true);  
} finally {  
receiveExecutor.shutdown(); 
receiveFuture=null;
receiveExecutor=null;
System.gc();
} [align=left][/align]

------解决方案--------------------------------------------------------
打印语句,属于非同步的,不能根据打印语句的先手顺序看实际的多线程的执行顺序
  相关解决方案