I created a send-receive datagram system for a game I have created in java (and LWJGL).
However, these datagrams often got dropped. That was because the server was waiting for various IO operations and other processing to be finished in the main loop, while new datagrams were being sent to it (which it was obviously not listening for).
To combat this, I have kept my main thread with the while true loop that catches datagrams, but instead of doing the processing in the main thread, I branch out into different threads.
Like this:
ArrayList<RecieveThread> threads = new ArrayList<RecieveThread>(); public void run(){ while (true){ //System.out.println("Waiting!"); byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); } //System.out.println("Recieved!"); String str = new String(packet.getData()); str = str.trim(); if (threads.size() < 50){ RecieveThread thr = new RecieveThread(); thr.packet = packet; thr.str = str; threads.add(thr); thr.start(); }else{ boolean taskProcessed = false; for (RecieveThread thr : threads){ if (!thr.nextTask){ thr.packet = packet; thr.str = str; thr.nextTask = true; taskProcessed = true; break; } } if (!taskProcessed){ System.out.println("[Warning] All threads full! Defaulting to main thread!"); process(str, packet); } } } } That is creating a new thread for every incoming datagram until it hits 50 packets, at which point it chooses to process in one of the existing threads that is waiting for a next task - And if all threads are processing, it defaults to the main thread.
So my question is this: How many threads is a good amount? I don't want to overload anybody's system (The same code will also be run on players' clients), but I also don't want to increase system packet loss.
Also, is different threads even a good idea? Does anybody have a better way of doing this?
Edit: Here is my RecieveThread class (class is 777 lines long):
String str; DatagramPacket packet; boolean nextTask = true; public void run(){ while (true){ ////System.out.println("CLIENT: " + str); //BeforeGame while (!nextTask){ //Nothing } <Insert processing code here that you neither know about, nor care to know about, nor is relevant to the issue. Still, I pastebinned it below> } }
java.util.concurrent.Executorand friends.