I wrote a Bluetooth API to connect to an external accessory. The way to design an API is that there are many blocking calls like getTime , setTime , getVolume , setVolume , etc. How they work, they create a payload for sending and calling a method called sendAndReceive() , which does some preparatory work, and ultimately does the following:
byte[] retVal = null; BluetoothSocket socket = getSocket(); // write socket.getOutputStream().write(payload); // read response if(responseExpected){ byte[] buffer = new byte[1024]; // buffer store for the stream int readbytes = socket.getInputStream().read(buffer); retVal = new byte[readbytes]; System.arraycopy(buffer, 0, retVal, 0, readbytes); } return retVal;
The problem is that sometimes this device becomes slow or unresponsive, so I want to put a timeout on this call. I tried several methods to put this code in the thread \ future task and run it with a timeout, for example:
FutureTask<byte[]> theTask = null; // create new task theTask = new FutureTask<byte[]>( new Callable<byte[]>() { @Override public byte[] call() { byte[] retVal = null; BluetoothSocket socket = getSocket(); // write socket.getOutputStream().write(payload); // read response if(responseExpected){ byte[] buffer = new byte[1024]; // buffer store for the stream int readbytes = socket.getInputStream().read(buffer); retVal = new byte[readbytes]; System.arraycopy(buffer, 0, retVal, 0, readbytes); } return retVal; } }); // start task in a new thread new Thread(theTask).start(); // wait for the execution to finish, timeout after 6 secs byte[] response; try { response = theTask.get(6L, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new CbtException(e); } catch (ExecutionException e) { throw new CbtException(e); } catch (TimeoutException e) { throw new CbtCallTimedOutException(e); } return response; }
The problem with this approach is that I cannot repeatedly exclude exceptions from the call method, and since some of the methods throw exceptions that I want to send back to the API client, I cannot use this methodology.
Can you recommend another alternative? Thanks!
ekatz source share