Below is my run()
of my Server Socket Thread which will be running as Executors.newWorkStealingPool().submit(() -> mainServer.run());
and accepts client connections. It runs fine but Sonar
is complaining it as Bug
of Type Loops should not be infinite (squid:S2189)
class MainServer {
private final ServerSocket serverSocket;
private final boolean checkClientCerts;
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MainServer.class.getName());
private final int threadPoolSize;
private boolean running;
private ExecutorService executorService;
MainServer(int port, boolean checkClientCerts, int threadPoolSize, InetAddress bindAddress) throws IOException {
LOG.debug("Locating server socket factory for SSL...");
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
LOG.debug("Creating a server socket on port " + port);
SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(port, 0, bindAddress);
this.checkClientCerts = checkClientCerts;
this.threadPoolSize = threadPoolSize;
}
void run() {
running = true;
DefaultThreadFactory threadFactory = new DefaultThreadFactory("SSLHandshake");
executorService = new ShutdownThreadPoolExecutor(threadPoolSize,threadFactory);
while (running) {
Socket clientSocket;
try {
clientSocket = serverSocket.accept();
MainServerHandshakeThread handshakeThread = new MainServerHandshakeThread(clientSocket, this);
executorService.submit(handshakeThread);
} catch (IOException ex) {
LOG.error("Error accepting connection",ex);
}
}
}
public void shutdown() {
LOG.info("Stopping main server...");
running = false;
try {
if (serverSocket!=null) {
serverSocket.close();
}
} catch(IOException ex) {
LOG.debug("Failed to close socket",ex);
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(500, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
LOG.info("Main server stopped...");
}
}
Can someone please help me how to optimize above block of code to get rid of Sonar complaint?