Reputation: 13
I have J2EE project which uses framework struts2 and Tomcat. There are two actions: "start task" and "stop task". As I understand it, when a user runs the task "start task", then Tomcat starts a thread where the task is executed. The user can click "stop task" and then Tomcat starts the second thread where it needs to stop the first thread. Method of action where execute task very big. There are queries to DB and calculations. In order to stop thread I use interrupt()
of first thread but interrupt()
just change value of flag but the code in the method continues to run. I check interrupt flag (Thread.currentThread().isInterrupted()
) in different parts of method and if thread is interrupted then I use "return". Is there any other way?
Upvotes: 1
Views: 661
Reputation: 115358
Your implementation is correct. The way you are using is recommended. Other way is to use Thread.stop()
but this method is deprecated since java 1.1 and no-one should use it. This method is like kill -9
in Unix, i.e. it just kills the thread that may cause program to enter inconsistent state and can produce resource leak.
Obviously you can improve your design. You said that the method is very big. Generally method should not exceed 20 lines. Well, 50 is the maximum. If your method is so big, break it into smaller tasks and check isInterrupted()
before each task.
Going forward to the OO world: create interface Task
with method perform()
. (Names do not matter. You can choose other names).
Each subtask should be implemented in separate class and should implement this interface. Then Create special InterruptionChecker
that implements Task
and holds other task. It checks whether thread is interrupted and if not, runs payload task. This pattern is called wrapper or decorator.
Now your "big" method should just run all tasks in loop. When thread is iterrupted the no new tasks is performed.
Upvotes: 1