The InputStream
of my Process
should attach and detach whenever the user wants to see it or not. The attaching works fine, but the detach fails. Default answer to interrupt the readLine()
method is always to close the stream, but I cant in this case or the Process
will finish or at least not available for future attachments. This is how the stream is read:
BufferedReader reader = new BufferedReader(new InputStreamReader(getProcess().getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
To detach I tried some stuff:
- Close any of the streams, failed: close method is blocking and waits for the readLine()
- Implement another stream to send null / abortion value with
SequenceInputStream
, failed: when oneInputStream
was waiting for input, the other was not even called Use reflections to unlock the
read()
method inside any of the streams, failed: not sure why, but did not work. Should we go on with this try? Here is the sourcecode:try { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); Field fdecoder = stream.getClass().getDeclaredField("sd"); fdecoder.setAccessible(true); modifiers.setInt(fdecoder, 1); StreamDecoder decoder = (StreamDecoder) fdecoder.get(stream); Field flock = decoder.getClass().getSuperclass().getDeclaredField("lock"); flock.setAccessible(true); modifiers.setInt(flock, 1); Object lock = (Object) flock.get(decoder); synchronized (lock) { lock.notifyAll(); } } catch (NoSuchFieldException | IllegalAccessException e) { Wrapper.handleException(Thread.currentThread(), e); }
Not sure how I can fix this. Could you help me interrupting the readLine()
method without closing the stream, simple and performant? Thanks.
Edit: What do I mean by "performant"? My application has not much users, but a lot of processes. The answer by @EJP is not wrong - but unperformant in the case of my application. I cannot have hundreds of threads for hundreds of processes, but I can have as many processes as I have users watching. That's why I try to interrupt the process gracefully. Fewer threads, less running/blocked threads. Here is the application described (https://i.sstatic.net/KIb9G.png) The Thread that sends the information to the user is the same that reads the input.