Some of the input - output objects like InputStream
cannot be interrupted and the source cannot be closed during reading, writing.
Example:
class InputStreamOperation1 implements Runnable
{
static InputStream stream;
InputStreamOperation1(InputStream stream) { this.stream = stream; }
public void run()
{
System.out.println("InputStreamOperation - the beginning");
try
{
stream.read(); //blocking operation
} catch (Exception e)
{
System.out.println("InputStreamOperation interrupted");
}
System.out.println("InputStreamOperation - the end");
}
}
Trying to interrupt:
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting InputStream");
f.cancel(true); // Interrupts if running
System.out.println("Interrupt sent to InputStream");
Trying to close the source
Future<?> f = executor.submit(new InputStreamOperation1(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Closing source in InpuStream");
try
{
System.in.close();
} catch (IOException e)
{
System.out.println("Error during closing InputStreamOperation");
}
System.out.println("Closed source in InputStream");
Both solutions are not working. It interrupts or closes after reading at least one letter.
My question: it there any way to interrupt blocking read()
operation or close the source during this blocking operation?
I found something similar here - Is it possible to read from a InputStream with a timeout?. I want to know whether is any other solution (especially with interrupts or closing source) to stop the thread or the only one is connected with that tricky manner.