I am writing a (TCP v4) server that accepts connections for all available network interfaces.
Server gets a value frim thouthends of clients and searches/sorts data based on that value. Then, returns an array of string values back to clients.
What is the best choice for this task: ExecutorService vs ForkJoinPool vs standard threads?
Here is the code for standard threads, is there anything to improve?
while (!Thread.currentThread().isInterrupted()) {
try (Socket socket = new ServerSocket(init()).accept()) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try (BufferedReader fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream()); ) {
outToClient.write(autocomplete(fromClient.readLine()).getBytes("US-ASCII"));
} catch (IOException e) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, e.getMessage()); }
}
}
}).start();
} catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex.getMessage()); }
}
Code for ExecutorService:
final ExecutorService service = Executors.newCachedThreadPool();
while(!Thread.currentThread().isInterrupted()) {
service.submit(new Runnable() {
public void run() {
try (Socket socket = new ServerSocket(init()).accept();
BufferedReader fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());) {
outToClient.write(autocomplete(fromClient.readLine()).getBytes("US-ASCII"));
} catch (IOException e) {
service.shutdown();
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, e.getMessage());
}
}
});
}
Or should I use ForkJoinPool...?