我正在製作一個接收HTTP請求的Java應用程序。對於每個進入的請求,我都會啓動一個新線程,並在該線程中讀取請求並執行必要的操作。但是,我想阻止用戶執行「Slow Loris Attack」,所以我正在考慮給線程一個maxTime
值。如果線程比maxTime
花費的時間更長,則無論如何都將終止。所以它也會阻塞緩慢的連接,這是不是的一個問題。Java - 在不阻塞主線程的情況下停止時間片
但是,我不知道正確的做法是什麼。我試過下面的代碼,但是這段代碼阻止了我的主線程。我正在尋找一種方式來做類似的事情,而不會阻塞主線程。
代碼:
/**
* 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() ;'在阻塞語句後立即執行'executor.submit(t).get(10,TimeUnit.SECONDS);'並嘗試? – harshavmb
@harshavmb我不明白這將如何解決我的問題..我確實嘗試了它,並且像我預測的那樣墜毀了。因爲當您發送第二個HTTP請求時,池將不會接受它,因爲它已關閉。 'java.util.concurrent.RejectedExecutionException' – Guido
你爲什麼在你的主線程中調用Future#?你甚至不用做任何事情。另外,TimeOutException不會停止任務。 – matt