I am building a UDP-based application that receives and sends multiple packets.
I could build a new DatagramPacket
for each send, or I recycle one instance for the life of my application.
DatagramPacket
? (e.g. memory-allocation)This is an old question, but I wanted to set the record straight. Perhaps this behavior has changed in the intervening years. Yes, you can reuse a DatagramPacket and avoid allocating a new one. Call DatagramPacket.setData() each time. You can only use the packet in one thread at a time, and only for the address that you created it for.
Is it worthwhile? Maybe. Modern GCs are quite efficient at reclaiming short-lifetime objects. I've run a basic performance test sending from one thread and receiving in another, and it made no difference.