從servlet啓動線程的推薦方式是什麼?我們如何從一個servlet開始一個線程?
示例:一位用戶向遊戲房間發佈新聊天消息。我想向所有連接到房間的其他玩家發送推送通知,但它不必同步發生。就像:
public MyChatServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
{
// Update the database with the new chat message.
final String msg = ...;
putMsgInDatabaseForGameroom(msg);
// Now spawn a thread which will deal with communicating
// with apple's apns service, this can be done async.
new Thread() {
public void run() {
talkToApple(msg);
someOtherUnimportantStuff(msg);
}
}.start();
// We can send a reply back to the caller now.
// ...
}
}
我使用Jetty,但我不知道在這種情況下Web容器真的很重要。
謝謝
好吧,你會做一個包裝ThreadPoolExecutor實例的單例,並且所有的servlet實例都將它們的任務轉儲到那裏? – user3203425
@ user3203425:是的,這對我來說似乎很合理。您可能希望有多個執行者用於不同的目的,因此其中一個執行者的負載不會影響另一個執行者。仔細調整池和隊列大小,以使它們符合您的預期流量速率和可接受的任務延遲。 –
好吧,我沒有在我的項目中使用servlet 3.0,我決定使用threadpoolexecutor,它似乎運行良好。 – user3203425