views:

65

answers:

3

I have a simple UDP server that creates a new thread for processing incoming data. While testing it by sending about 100 packets/second I notice that it's memory usage continues to increase. Is there any leak evident from my code below?

Here is the code for the server.

public class UDPServer
{
    public static void main(String[] args)
    {
        UDPServer server = new UDPServer(15001);
        server.start();
    }

    private int port;

    public UDPServer(int port)
    {
        this.port = port;
    }

    public void start()
    {
        try
        {
            DatagramSocket ss = new DatagramSocket(this.port);

            while(true)
            {   
                byte[] data = new byte[1412];
                DatagramPacket receivePacket = new DatagramPacket(data, data.length);
                ss.receive(receivePacket);
                new DataHandler(receivePacket.getData()).start();
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}

Here is the code for the new thread that processes the data. For now, the run() method doesn't do anything.

public class DataHandler extends Thread
{
    private byte[] data;

    public DataHandler(byte[] data)
    {
        this.data = data;
    }

    @Override
    public void run()
    {
        System.out.println("run");
    }

}
A: 

Why do you have a infinite while loop in your code. Can't you run it in a separate thread. Also, this line byte[] data = new byte[1412]; will allocate some bytes which will not be released till the infinte loop is going on.

prasrob
The loop will wait to receive an incoming packet, create a new thread to process the data and then start the loop again to wait for another incoming packet.
Trevor
'new byte[1412]; will allocate some bytes which will not be released'. Incorrect. This reference will be released every time around the loop. The other reference in the Thread will be released when the thread exits. I agree with the other poster that you shouldn't use a thread per packet. Depending on what the processing is you may not need a new thread at all: otherwise think about using a thread per remote SocketAddress.
EJP
+4  A: 

Of couse, you're allocating (at least) 1412 bytes of new memory each loop. You'll see an increase of memory usage until GC kicks in and cleans all unused allocated data.

Use a memory profiler like Java VisualVM to visualize and analyse the behaviour.

Mavrik
JConsole would be better in this case as it includes a view of all eden, survivor, and old-gen heap sizes. Plus, you can strongly suggest a gc.
Tim Bender
A: 

You're allocating a new thread for every single packet. Thread allocation is not cheap. You could try to use a thread pool and just hand the packets off to worker threads taken from the pool (look at java.util.concurrent for some great classes to help here).

dty