I have a UDP server that receives packets at 40 pkts per seconds. The main loop is below:
public void serve() {
while(true) {
ByteBuffer bytes = ByteBuffer.allocate(1024);
bytes.clear();
channel.receive(bytes);
THandler th = new THandler(bytes);
th.start();
}
}
Channel Initialization:
private final DatagramChannel channel ;
channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(port));
The class THandler extends a thread class and it filters the message against a regular expression and then finds an id from the matching message. This id is then compared to a list of subscribers (approx 300k). followed by a db select followed by an update.
public void run() {
if (!this.isValidLog()){ //does a regular expression match
return;
}
String subsId = this.getSubscriberId(); // extracts the id from message
if (this.isServiceSubscribed(subsId)) { // compares in a list of subscribers
usageDetails = this.getServiceUsage(subsId); // db Query
if(usageDetails.isFeatureAvailable()){
usageDetails.updateUsageCounter(); // db Update
}
}
}
I have tried using ExecutorService also. But the problem is that I run out of CPU time with 99.6% or more in user.
Any inputs on how to improve the performance of the server and code are most welcome.