Reputation: 1911
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?
Upvotes: 2
Views: 366
Reputation: 66196
Maybe I misunderstood something, but I think you want to use Observer pattern.
Upvotes: 0
Reputation: 1779
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();
}
Upvotes: 0
Reputation: 339975
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
.
Upvotes: 1
Reputation: 83943
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.
Upvotes: 0
Reputation: 3441
You need to use java.nio package, check out here http://rox-xmlrpc.sourceforge.net/niotut/
Upvotes: 0
Reputation: 2670
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.
Upvotes: 1