What is the right way to stop a thread waiting for network activity?

This question has undoubtedly been asked in various forms in the past, but not so much for a specific scenario.

What is the most correct way to stop a thread that is blocking while waiting for a network message to be received over UDP.

For example, let's say I have the following topic:

public class ClientDiscoveryEngine extends Thread { private final int PORT; public ClientDiscoveryEngine(final int portNumber) { PORT = portNumber; } @Override public void run() { try { socket = new DatagramSocket(RECEIVE_PORT); while (true) { final byte[] data = new byte[256]; final DatagramPacket packet = new DatagramPacket(data, data.length); socket.receive(packet); } } catch (SocketException e) { // do stuff 1 } catch (IOException e) { // do stuff 2 } } } 

Now, would it be more appropriate to use the interrupt() method? For example, adding the following method:

 @Override public void interrupt() { super.interrupt(); // flip some state? } 

My only problem is that socket.receive() not a lock interrupt method? The only way I thought was to implement the interrupt method, as mentioned above, in this method, call socket.close() , and then serve it in the run method in catch for a SocketException . Or maybe instead of while(true) use some kind of state that falls into the interrupt method. Is this the best way? Or is there a more elegant way?

thanks

+4
source share
4 answers

The receiving method does not seem to be interrupted. You can close the socket: javadoc says:

Any thread that is currently blocked in receive(java.net.DatagramPacket) on this socket will throw a SocketException

You can also use setSoTimeout to make a receive method only for a short period of time. After the method returns, your thread can check if it was interrupted, and try again to get it again in this small amount of time.

+4
source

To stop the thread, you should not interrupt or stop the user in java. The best way, as you said at the end of your question, is for the loop inside the main method to be controlled by a flag that you can raise as needed.

Here is an old link about it: http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

Other methods of stopping the flow become obsolete and do not provide such control as this. In addition, this may have changed a bit with the help of the executing services, I did not have time to find out more about it.

In addition, if you want your thread to be blocked in some I / O state while waiting for a socket, you must give your socket a connection and read time ( setSoTimeout method).

Regards, StΓ©phane

+2
source

This is one of the easiest. If it is locked in the UDP socket, send a UDP message to the socket that instructs the receiving stream to stop.

Rgds, Martin

0
source

All Articles