1

I'm hoping to improve performance by improving small lags caused by garbage collection while receiving packets. I have a simple DatagramSocket that receives data like so:

DatagramSocket sock;
try {
    sock = new DatagramSocket(port);
    sock.setReuseAddress(true);
} catch (SocketException e) { }

DatagramPacket pack = null;
byte[] buff = new byte[SIZE];

while(!sock.isClosed()){
    try{
        pack = new DatagramPacket(buff, buff.length());
        sock.receive(pack);
    } catch (IOException e) { }
}

The code above works well except that there ends up being a lot of calls to collect garbage (as seen in my LogCat viewer). I know that in order to avoid garbage collection you want to try not to allocate memory, but does anyone see a good way to do that with the above code and still achieve the same results?

I looked at this thread and this thread but am not sure how they would map to my particular situation. I also saw this suggestion to call GC but in this case GC is already being executed many times in the interim.

Any suggestions would be greatly appreciated!

Community
  • 1
  • 1
user1205577
  • 2,388
  • 9
  • 35
  • 47
  • anything you create `new` causes GC once the object is no longer needed. You do `new` in a loop = a lot of objects that are no longer required. If you can avoid that and re-use the object you get less GC. See @jellyfication answer how to do that – zapl Apr 19 '12 at 22:39

1 Answers1

0

What about this ?

DatagramSocket sock;
try {
    sock = new DatagramSocket(port);
    sock.setReuseAddress(true);
} catch (SocketException e) { }

DatagramPacket pack = null;
byte[] buff = new byte[SIZE];
pack = new DatagramPacket(buff, buff.length());

while(!sock.isClosed()){
    try{
        pack.setData(buff, 0, buff.length()); // Maybe you can comment this line out. If the buffer doesn't change its irrelevant
        sock.receive(pack);
    } catch (IOException e) { }
}

Do you need to keep constructing new DatagramPacket objects ? The size of buffer dosen't change, so you could keep it unchanged.

jellyfication
  • 1,595
  • 1
  • 16
  • 37
  • That was a good suggestion, but I just tried it out and am still getting the heavy garbage collection. If I pause it, the collection stops and when I restart it, so does the GC. – user1205577 Apr 19 '12 at 22:37
  • Commenting out this line dosen't help ? pack.setData(buff, 0, buff.length());.. I mean the buffer gets rewritten each time so there is no need for that – jellyfication Apr 19 '12 at 22:38
  • I seems that inside DatagramSocket.receive(DatagramPacket p) are some allocations http://www.java2s.com/Open-Source/Android/android-core/platform-libcore/java/net/DatagramSocket.java.htm – jellyfication Apr 19 '12 at 22:52
  • Thanks for the link! I'll do some digging and see if there might be a way to rework the problem. – user1205577 Apr 19 '12 at 23:45