Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I wake a thread that has blocked because of a call to DatagramSocket.receive()?

I have a thread that blocks on a UDP packet, and I need to be able to tell it to forget about that packet and do something else, all before the receive timeout happens. Is there any way to do this?

like image 773
alexgolec Avatar asked Feb 27 '11 17:02

alexgolec


2 Answers

Use a DatagramChannel to read your UDP packets, and interrupt the reading thread. As per the documentation of Thread.interrupt (and DatagramChannel), the read operation will then throw a ClosedByInterruptException.

like image 98
JB Nizet Avatar answered Oct 31 '22 00:10

JB Nizet


JB has posted one part of the solution. But if in case you are not using NIO channels, the solution AFAIK here would be to close the socket in consideration and handle it likewise in your runnable/callable. I did something similar a while back with TCP sockets, in case if you are interested. The feasibility of the solution again depends on whether closing the socket would be acceptable in your case or not. In that case, going with the NIO solution would make much more sense.

like image 25
Sanjay T. Sharma Avatar answered Oct 31 '22 00:10

Sanjay T. Sharma