DatagramPacket Sender Thread running too fast
I've written a Java thread (Runnable) to basically store a list of DatagramPackets and if the size of the list is > 0 it will send the first item on the list.
It seems that unless I put a large sleep inside the run method the thread will become unresponsive
public void run()
{
while ( true )
{
if ( _packetQ.size() > 0)
{
try
{
_so开发者_如何学运维cket.send( _packetQ.remove() );
}
catch ( IOException ex )
{
System.err.println( "Error sending packet" );
System.err.println( ex );
}
}
}
}
_packetQ is a linked list of datagram packets.
Is their anyway I can stop the thread locking up or get it to only run when the packetQ.size() > 0
Thank SO
UPDATE: Oh dear the packets weren't even being pushed to the queue because of an error in the code, Just wasted an hour debugging that. Thanks for the responses**
You can replace your linked list with a LinkedBlockingQueue
which waits silently until new data arrives.
You could add something like this inside your first while (true)
loop:
while (_packetQ.size() == 0) {
Thread.sleep(10);
}
Prefer to use a LinkedBlockingQueue
instead though, see this answer as an example.
I am not sure why you would want to background sending of datagrams and why you don't just send the data immediately in the calling thread. The approach you have taken is useful for blocking IO or even NIO but not some much for UDP. UDP doesn't wait so there is little value in passing this work to another thread.
I suggest you write the loop this way;
- you can stop the thread with an interrupt.
- wait for data to ready to send.
- print the stack trace for an exception.
sample code
private final BlockingQueue<DatagramPacket> _packetQ = new LinkedBlockingQueue<DatagramPacket>();
public void run() {
while (!Thread.interrupted()) {
try {
_socket.send(_packetQ.take());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Get rid of the size test and just let it block in the remove)) method. Make sure you use a queue implementation with blocking behaviour of course as suggested in other answers. At the moment you are just spinning pointlessly while size() == 0.
精彩评论