Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Why not try something like</p> <pre><code>public class ReadTask extends Thread { private byte[] mResultBuffer; private Exception mCaught; private Thread mWatcher; public ReadTask(Thread watcher) { mWatcher = watcher; } public void run() { try { mResultBuffer = sendAndReceive(); } catch (Exception e) { mCaught = e; } mWatcher.interrupt(); } public Exception getCaughtException() { return mCaught; } public byte[] getResults() { return mResultBuffer; } } public byte[] wrappedSendAndReceive() { byte[] data = new byte[1024]; ReadTask worker = new ReadTask(data, Thread.currentThread()); try { worker.start(); Thread.sleep(6000); } catch (InterruptedException e) { // either the read completed, or we were interrupted for another reason if (worker.getCaughtException() != null) { throw worker.getCaughtException(); } } // try to interrupt the reader worker.interrupt(); return worker.getResults; } </code></pre> <p>There is an edge case here that the Thread calling <code>wrappedSendAndReceive()</code> may get interrupted for some reason other than the interrupt from the ReadTask. I suppose a done bit could be added to the ReadTask to allow the other thread to test if the read finished or the interrupt was caused by something else, but I'm not sure how necessary this is.</p> <p>A further note is that this code does contain the possibility for data loss. If the 6 seconds expires and some amount of data has been read this will end up being discarded. If you wanted to work around this, you'd need to read one byte at a time in ReadTask.run() and then appropriately catch the InterruptedException. This obviously requires a little rework of the existing code to keep a counter and appropriately resize the read buffer when the interrupt is received.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload