Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are running while loop inside <strong><em>contextInitialized()</em></strong> method which is wrong. <strong><em>contextInitialized()</em></strong> is invoked by Servlet Container as part of the application startup, having while loop there will block your app start. </p> <p>Modified the code such the ContextListener will start one daemon thread which publishes the messages to the watchers</p> <pre><code>@WebListener public class ChatPushService implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { final List&lt;AsyncContext&gt; watchers = new ArrayList&lt;AsyncContext&gt;(); sce.getServletContext().setAttribute("watchers", watchers); // store new messages not published yet Queue&lt;String&gt; messages = new ConcurrentLinkedQueue&lt;String&gt;(); sce.getServletContext().setAttribute("messages", messages); new chatManager(sce.getServletContext()).start(); //START DAEMON } } public class ChatManager implements Runnable { ServletContext servletCtx; public ChatManager(ServletContext ctx) { this.servletCtx = ctx; } public void run() { List&lt;AsyncContext&gt; watchers = (List&lt;AsyncContext&gt;) servletCtx.getAttribute("watchers"); Queue&lt;String&gt; messages = (Queue&lt;String&gt;)appScope.getAttribute("messages"); Executor messageExecutor = Executors.newCachedThreadPool(); final Executor watcherExecutor = Executors.newCachedThreadPool(); while(true) { if(!messages.isEmpty()) { System.out.println("notEmpty"); String message = messages.poll(); messageExecutor.execute(new Runnable(){ @Override public void run() { for(final AsyncContext aCtx : watchers){ watcherExecutor.execute(new Runnable(){ @Override public void run() { try { aCtx.getResponse().getWriter().print("brrrrr"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } } }); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload