Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a thread in a view scoped bean?

In our application when a user clicks on commandlink, a pop up is generated. This click will pass an id to process.

My managed bean is viewscoped and I am creating a thread to do some tasks.

In a scenario where a user clicks on the link a pop up is generated and the thread has started executing jobs, say the user closes the pop up and tries to click the link providing a different id this time. My problem is the previous thread which was started is not being destroyed. I can still get the latest id details as a response but the previous thread still executes jobs.

I would like to know if there is a way to terminate the previous instance thread on a new request. I know I can achieve this using sessionscoped but popups are being opened in the same session.

like image 436
PermGenError Avatar asked Aug 24 '12 15:08

PermGenError


1 Answers

just as a quick solution possible for your use case:

  • I'd use threadpool rather than creating new thread per request (as thread pooling idea is more efficient + provided in standard API)
  • then you can easily stop any running thread in pool, solution I've found on: http://www.coderanch.com/t/234197/threads/java/stopping-runnable-ThreadPoolExecutor => question contains sample for threadpool implementation and the 1.st answer gives you the solution

calling:

boolean cancel(boolean mayInterruptIfRunning)

In your case the call should use:

mayInterruptIfRunning=true

The only quesion left is: Where to keep the Future reference? :)
We can discuss that if you want as well :)

like image 75
Peter Butkovic Avatar answered Sep 21 '22 18:09

Peter Butkovic