开发者

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

开发者 https://www.devze.com 2023-02-14 05:44 出处:网络
I have a thread that blocks on a UDP packet, and I need to be able to tel开发者_运维问答l it to forget about that packet and do something else, all before the receive timeout happens. Is there any way

I have a thread that blocks on a UDP packet, and I need to be able to tel开发者_运维问答l it to forget about that packet and do something else, all before the receive timeout happens. Is there any way to do this?


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.


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.


Set a much shorter read timeout and have your read method loop the correct number of times before it considers a read timeout to have happened. In the other (n-1) cases have it check Thread.isInterrupted().

0

精彩评论

暂无评论...
验证码 换一张
取 消