I'm making a Java application which receives HTTP requests. For each request which comes in, I start a new thread, and in that thread I'm reading the request and performing the necessary actions. However, I want to prevent the users from performing a "Slow Loris Attack", so I was thinking about giving a thread a maxTime
value. If the thread takes longer than the maxTime
it will terminate no matter what. So it will also block slow connections, which is not a problem.
However, I don't know what the right way is to do this. I've tried the following code, but this code is blocking my main thread. I'm looking for a way to do something similar like this, without blocking the main thread.
Code:
/**
* Executor which is used for threadpools.
*/
private ExecutorService executor;
/**
* Constructor for the class RequestReceiver.
* Initializes fields.
*/
public RequestReceiver() {
this.executor = Executors.newFixedThreadPool(200);
}
@Override
public void run() {
try {
this.serverSocket = new ServerSocket(port);
} catch (IOException ex) {
Logger.getInstance().logText("Could not start server on port: " + port);
return;
}
Logger.getInstance().logText("Server running at port: " + port);
try {
while (shouldContinue) {
Socket client = serverSocket.accept();
HTTPRequestHandler handler = new HTTPRequestHandler(client);
Thread t = new Thread(handler);
executor.submit(t).get(10, TimeUnit.SECONDS); //This line is blocking
}
} catch (IOException ex) {
Logger.getInstance().logText("Server is shutdown");
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
Logger.getInstance().logText("Thread took too long, it's shutdown");
}
}
executor.shutdown();
immediately after blocking statementexecutor.submit(t).get(10, TimeUnit.SECONDS);
and try? – harshavmbjava.util.concurrent.RejectedExecutionException
– Guido.get()
isn't blocking your main thread. – matt