卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

Terminate java thread in web application

My web application (on Tomcat) provides “on the fly” logic execution functionality.
The problem is the “on the fly” logic can contains infinite loop , or something long duration.

My solution is timeout: to run the “on the fly” logic in a new daemon thread and go back main thread in timeout, p-code as below:

 ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory(){
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        result.setDaemon(true);
        return t;
    }});

 Future<Object> future = executor.submit(callable/* 'on the fly' callable: it can be infinite loop, the callable is out of my control */);
 //Back to main thread
 return future.get(timeout, TimeUnit.MILLISECONDS);

However, the daemon thread is still running, although future.get() returns in timeout. The daemon is terminated until Tomcat stops.

Now my latest solution is create a new Java process Runtime.getRuntime().exec("java MyProgram"). MyProgram contains future.get() shown before. The daemon is terminated once main thread quits as expected.

I am here to ask more elegant solution to terminate thread in web application. The new Java process is heavy and out control of web application.

Thanks!

Upvotes: 0

Views: 318

Answers (1)

Maulik Patel
Maulik Patel

Reputation: 2802

threading in a managed environment is generally a bad idea. why not use some sort of abstraction like JMS to start a background handler every time someone sends a request ? that way you can control the number of active threads (jms pool size)

Upvotes: 2

Related Questions