Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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?
Java
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:
Java
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...?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900