Cancel or Pause a Thread’s execution – the basics.

I’ve thought about this wishing to be able to stop some processes while running on some timers, and to stop them safely and clean. For instance a process would download some large amount of data, then analyze it, maybe store it, then send some mails or notifications. Basically a complex list of things that might take more the few seconds to run, up to minutes or more.

How can you safely stop a process like this? I’m sure that even if you didn’t do it so far and think a bit you might very well find solutions.

Basically, in what I did, there is only one simple trick. The idea is to constantly call a method that will throw and exception if the status is CANCEL. In more details, implement the Runnable, implement run() as final and call from there an abstract method where the actual implementation of the process will be i.e. execute(). Then in your implementation, anyplace where you can afford to stop the execution make calls to checkInterruption(), which will throw an exception in case the process was canceled, or if paused it will do a wait() until resumed.

I found this solution as being really easy to implement and use, safely enough, clean, reusable, scalable.

You can find it here as a Java implementation: https://github.com/bogdanudrescu/SimpleThreadsAPI

The API is straight forward: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/InterruptibleRunnable.java

public interface InterruptibleRunnable extends Runnable {

	void cancel();

	void pause();

	void resume();

	public InterruptibleRunnableState getState();

	public InterruptibleRunnableState getRealState();

	public void addPropertyChangeListener(PropertyChangeListener listener);

	public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);

	public float getPercentCompleted();
}

https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/InterruptibleRunnableState.java

public enum InterruptibleRunnableState {

	NOT_RUNNING,

	RUNNING,

	PAUSED,

	CANCELED
}

OK, the actual code looks more beautiful, but to save some space here I remove the comments. 🙂

Quick look on the actual class implementation: https://github.com/bogdanudrescu/SimpleThreadsAPI/blob/master/src/grape/simple/threads/AbstractInterruptibleRunnable.java

It also contains a very simple test sample on how to use it.

For a bit more complex example please read the next article: Simple Threads – a bit more complex approach

I called my package grape simple because my wife really love grapes. We have the custom each year to make wine, which we froze it on the spot. We can thus open the bottles at any time and it will be really sweet and with no alcohol.

Autumn Grape

Advertisements