Interrupting / stopping a stream with a socket I / O lock function

At some point in my server application, I want to stop some threads that perform I / O blocking operations.

For example, one of them has the following run() method:

 public void run() { System.out.println("GWsocket thread running"); int len; byte [] buffer = new byte[1500]; try { this.in = new DataInputStream(this.socket.getInputStream()); this.out = new DataOutputStream(this.socket.getOutputStream()); running = true; while (running){ len = in.read (buffer); if (len < 0) running = false; else parsepacket (buffer, len); } }catch (IOException ex) { System.out.println("GWsocket catch IOException: "+ex); }finally{ try { System.out.println("Closing GWsocket"); fireSocketClosure(); in.close(); out.close(); socket.close(); }catch (IOException ex) { System.out.println("GWsocket finally IOException: "+ex); } } } 

If I want to stop the thread executing this code, what should I do?

Here they show how to do it ( How to stop a thread that is waiting for long periods of time (for example, for input)? ), But I do not understand what they mean:

For this method to work, it is important that any method that catches an interrupt exception and is not ready for an immediate solution repeats the exception. We say repeating, not repeating, because it is not always possible to rebuild an exception. If the method that catches the thrown exception does not declare this (checked) exception, then it must "relive itself" using the after-spell: Thread.currentThread (). interrupt ();

Can someone tell me? Some code examples would be greatly appreciated.

+4
source share
2 answers

The solution described by Peter Lory, as well as seen here , should close the socket.

With nio, you can also use the SocketChannel , which is interruptible and allows you to use the standard Java interrupt model .

Calling the interrupt method of the Thread object will raise an InterruptedException that will stop even your blocking I / O operation.

+5
source

You can add a method like

 public void close() throws IOException { this.socket.close(); } 

and any blocking I / O will throw a SocketException.

You may need to set a flag of type closed , which you can check to see if a thrown exception should be expected.

BTW: You cannot be sure that you will receive discrete packets when reading. It is much better to read what you need and use BufferedInputStream to increase efficiency. Read blocks only if you don't need to parse the contents, for example. copy from socket to file.

eg. your reading can only get one byte or get the end of one packet and the start of another.

+6
source

Source: https://habr.com/ru/post/1432906/


All Articles