tags:

views:

53

answers:

6
DataInputStream in;

byte[] b = new byte[1024];
for (;;){
 in.read(b);
 //do something
}

I have the above code. In another thread i am handling some other events. In this thread i want to cancel the read operation shown in the above code. How can i do?

+1  A: 

What if you send from another thread some data

final byte[] TERMINATOR = ...;
in.Write(TERMINATOR)

The reading thread could in that case should not use a for loop, but check for the 'terminator' sequence.

_NT
A: 

You need to use java.nio package, check out here http://rox-xmlrpc.sourceforge.net/niotut/

whoi
A: 

You can either close the InputStream you’re reading from, or you can rework your code to only read data when there actually is any data to read—which might be nigh impossible when you are not controlling the writing side.

Bombe
+1  A: 

You need to use java.nio to read from your stream, at which point you can call thread.interrupt() from the other thread to interrupt any ongoing read.

Alnitak
A: 

You can reset the input stream if you wish :

DataInputStream in;

byte[] b = new byte[1024];
in.mark(b.length());
try {
for (;;){
 in.read(b);
 //do something
}
}
catch (InterruptedException e) {
in.reset();
}
Steve De Caux
I think you've missed the point - the real problem is how to cause the `InterruptedException` in the first place, and even then it probably wouldn't interrupt a `read()` which is blocked in the operating system.
Alnitak
A: 

Maybe I misunderstood something, but I think you want to use Observer pattern.

Roman