Mungunbat Enkhbayar
Mungunbat Enkhbayar

Reputation: 181

How to run a different thread in a servlet?

How do I run a different thread from a servlet? I have the below code in the init() method of the servlet.

FileThread myThread = new FileThread();
myThread.start();
myThread.run();     

FileThread is supposed to see some folder to check whether files were changed or not. So this thread is made to run in a loop. But it doesn't work as I expected. It freezes (server doesn't return HTML) the service of the server.

I want this thread to run on background and not to interfere with servlet`s process. How can I achive this?

Upvotes: 1

Views: 4917

Answers (2)

Eran Medan
Eran Medan

Reputation: 45735

Starting your own threads might be not the most recommended thing in a web environment, and in a Java EE one, it's actually against the spec.

Servlet 3.0 have Async support, see more here

For example

@WebServlet("/foo" asyncSupported=true)
   public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse res) {
            ...
            AsyncContext aCtx = request.startAsync(req, res);
            ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
            executor.execute(new AsyncWebService(aCtx));
        }
   }

   public class AsyncWebService implements Runnable {
        AsyncContext ctx;
        public AsyncWebService(AsyncContext ctx) {
            this.ctx = ctx;
        }
        public void run() {
            // Invoke web service and save result in request attribute
            // Dispatch the request to render the result to a JSP.
            ctx.dispatch("/render.jsp");
   }
}

Java EE 6 and 7 has @Asyncronous method invocations

And Java EE 7 has Concurrency Utilities (managed Executor service for example that you can use to submit tasks to)

Upvotes: 5

Bruno Reis
Bruno Reis

Reputation: 37822

You usually don't call .run() on a Thread, since it will make the run() method run on the current thread, not on the new thread! You said you have an infinite loop there, therefore the servlet won't ever finish initialization, therefore it won't serve any requests!

You need to just call .start() on the Thread object. This method will make the JVM launch a new thread of execution that will run the code in the run() method of that Thread object.

Upvotes: 6

Related Questions